Expressions
Every AST node in SQLGlot is represented by a subclass of Expression.
This module contains the implementation of all supported Expression types. Additionally,
it exposes a number of helper functions, which are mainly used to programmatically build
SQL expressions, such as sqlglot.expressions.select.
1""" 2## Expressions 3 4Every AST node in SQLGlot is represented by a subclass of `Expression`. 5 6This module contains the implementation of all supported `Expression` types. Additionally, 7it exposes a number of helper functions, which are mainly used to programmatically build 8SQL expressions, such as `sqlglot.expressions.select`. 9 10---- 11""" 12 13from __future__ import annotations 14 15import datetime 16import math 17import numbers 18import re 19import typing as t 20from collections import deque 21from copy import deepcopy 22from enum import auto 23 24from sqlglot.errors import ParseError 25from sqlglot.helper import ( 26 AutoName, 27 camel_to_snake_case, 28 ensure_collection, 29 ensure_list, 30 seq_get, 31 split_num_words, 32 subclasses, 33) 34from sqlglot.tokens import Token 35 36if t.TYPE_CHECKING: 37 from sqlglot.dialects.dialect import DialectType 38 39E = t.TypeVar("E", bound="Expression") 40 41 42class _Expression(type): 43 def __new__(cls, clsname, bases, attrs): 44 klass = super().__new__(cls, clsname, bases, attrs) 45 46 # When an Expression class is created, its key is automatically set to be 47 # the lowercase version of the class' name. 48 klass.key = clsname.lower() 49 50 # This is so that docstrings are not inherited in pdoc 51 klass.__doc__ = klass.__doc__ or "" 52 53 return klass 54 55 56class Expression(metaclass=_Expression): 57 """ 58 The base class for all expressions in a syntax tree. Each Expression encapsulates any necessary 59 context, such as its child expressions, their names (arg keys), and whether a given child expression 60 is optional or not. 61 62 Attributes: 63 key: a unique key for each class in the Expression hierarchy. This is useful for hashing 64 and representing expressions as strings. 65 arg_types: determines what arguments (child nodes) are supported by an expression. It 66 maps arg keys to booleans that indicate whether the corresponding args are optional. 67 68 Example: 69 >>> class Foo(Expression): 70 ... arg_types = {"this": True, "expression": False} 71 72 The above definition informs us that Foo is an Expression that requires an argument called 73 "this" and may also optionally receive an argument called "expression". 74 75 Args: 76 args: a mapping used for retrieving the arguments of an expression, given their arg keys. 77 parent: a reference to the parent expression (or None, in case of root expressions). 78 arg_key: the arg key an expression is associated with, i.e. the name its parent expression 79 uses to refer to it. 80 comments: a list of comments that are associated with a given expression. This is used in 81 order to preserve comments when transpiling SQL code. 82 _type: the `sqlglot.expressions.DataType` type of an expression. This is inferred by the 83 optimizer, in order to enable some transformations that require type information. 84 """ 85 86 key = "expression" 87 arg_types = {"this": True} 88 __slots__ = ("args", "parent", "arg_key", "comments", "_type", "_meta", "_hash") 89 90 def __init__(self, **args: t.Any): 91 self.args: t.Dict[str, t.Any] = args 92 self.parent: t.Optional[Expression] = None 93 self.arg_key: t.Optional[str] = None 94 self.comments: t.Optional[t.List[str]] = None 95 self._type: t.Optional[DataType] = None 96 self._meta: t.Optional[t.Dict[str, t.Any]] = None 97 self._hash: t.Optional[int] = None 98 99 for arg_key, value in self.args.items(): 100 self._set_parent(arg_key, value) 101 102 def __eq__(self, other) -> bool: 103 return type(self) is type(other) and hash(self) == hash(other) 104 105 @property 106 def hashable_args(self) -> t.Any: 107 args = (self.args.get(k) for k in self.arg_types) 108 109 return tuple( 110 (tuple(_norm_arg(a) for a in arg) if arg else None) 111 if type(arg) is list 112 else (_norm_arg(arg) if arg is not None and arg is not False else None) 113 for arg in args 114 ) 115 116 def __hash__(self) -> int: 117 if self._hash is not None: 118 return self._hash 119 120 return hash((self.__class__, self.hashable_args)) 121 122 @property 123 def this(self): 124 """ 125 Retrieves the argument with key "this". 126 """ 127 return self.args.get("this") 128 129 @property 130 def expression(self): 131 """ 132 Retrieves the argument with key "expression". 133 """ 134 return self.args.get("expression") 135 136 @property 137 def expressions(self): 138 """ 139 Retrieves the argument with key "expressions". 140 """ 141 return self.args.get("expressions") or [] 142 143 def text(self, key) -> str: 144 """ 145 Returns a textual representation of the argument corresponding to "key". This can only be used 146 for args that are strings or leaf Expression instances, such as identifiers and literals. 147 """ 148 field = self.args.get(key) 149 if isinstance(field, str): 150 return field 151 if isinstance(field, (Identifier, Literal, Var)): 152 return field.this 153 if isinstance(field, (Star, Null)): 154 return field.name 155 return "" 156 157 @property 158 def is_string(self) -> bool: 159 """ 160 Checks whether a Literal expression is a string. 161 """ 162 return isinstance(self, Literal) and self.args["is_string"] 163 164 @property 165 def is_number(self) -> bool: 166 """ 167 Checks whether a Literal expression is a number. 168 """ 169 return isinstance(self, Literal) and not self.args["is_string"] 170 171 @property 172 def is_int(self) -> bool: 173 """ 174 Checks whether a Literal expression is an integer. 175 """ 176 if self.is_number: 177 try: 178 int(self.name) 179 return True 180 except ValueError: 181 pass 182 return False 183 184 @property 185 def is_star(self) -> bool: 186 """Checks whether an expression is a star.""" 187 return isinstance(self, Star) or (isinstance(self, Column) and isinstance(self.this, Star)) 188 189 @property 190 def alias(self) -> str: 191 """ 192 Returns the alias of the expression, or an empty string if it's not aliased. 193 """ 194 if isinstance(self.args.get("alias"), TableAlias): 195 return self.args["alias"].name 196 return self.text("alias") 197 198 @property 199 def name(self) -> str: 200 return self.text("this") 201 202 @property 203 def alias_or_name(self): 204 return self.alias or self.name 205 206 @property 207 def output_name(self): 208 """ 209 Name of the output column if this expression is a selection. 210 211 If the Expression has no output name, an empty string is returned. 212 213 Example: 214 >>> from sqlglot import parse_one 215 >>> parse_one("SELECT a").expressions[0].output_name 216 'a' 217 >>> parse_one("SELECT b AS c").expressions[0].output_name 218 'c' 219 >>> parse_one("SELECT 1 + 2").expressions[0].output_name 220 '' 221 """ 222 return "" 223 224 @property 225 def type(self) -> t.Optional[DataType]: 226 return self._type 227 228 @type.setter 229 def type(self, dtype: t.Optional[DataType | DataType.Type | str]) -> None: 230 if dtype and not isinstance(dtype, DataType): 231 dtype = DataType.build(dtype) 232 self._type = dtype # type: ignore 233 234 @property 235 def meta(self) -> t.Dict[str, t.Any]: 236 if self._meta is None: 237 self._meta = {} 238 return self._meta 239 240 def __deepcopy__(self, memo): 241 copy = self.__class__(**deepcopy(self.args)) 242 if self.comments is not None: 243 copy.comments = deepcopy(self.comments) 244 245 if self._type is not None: 246 copy._type = self._type.copy() 247 248 if self._meta is not None: 249 copy._meta = deepcopy(self._meta) 250 251 return copy 252 253 def copy(self): 254 """ 255 Returns a deep copy of the expression. 256 """ 257 new = deepcopy(self) 258 new.parent = self.parent 259 return new 260 261 def append(self, arg_key, value): 262 """ 263 Appends value to arg_key if it's a list or sets it as a new list. 264 265 Args: 266 arg_key (str): name of the list expression arg 267 value (Any): value to append to the list 268 """ 269 if not isinstance(self.args.get(arg_key), list): 270 self.args[arg_key] = [] 271 self.args[arg_key].append(value) 272 self._set_parent(arg_key, value) 273 274 def set(self, arg_key, value): 275 """ 276 Sets `arg_key` to `value`. 277 278 Args: 279 arg_key (str): name of the expression arg. 280 value: value to set the arg to. 281 """ 282 self.args[arg_key] = value 283 self._set_parent(arg_key, value) 284 285 def _set_parent(self, arg_key, value): 286 if hasattr(value, "parent"): 287 value.parent = self 288 value.arg_key = arg_key 289 elif type(value) is list: 290 for v in value: 291 if hasattr(v, "parent"): 292 v.parent = self 293 v.arg_key = arg_key 294 295 @property 296 def depth(self): 297 """ 298 Returns the depth of this tree. 299 """ 300 if self.parent: 301 return self.parent.depth + 1 302 return 0 303 304 def iter_expressions(self) -> t.Iterator[t.Tuple[str, Expression]]: 305 """Yields the key and expression for all arguments, exploding list args.""" 306 for k, vs in self.args.items(): 307 if type(vs) is list: 308 for v in vs: 309 if hasattr(v, "parent"): 310 yield k, v 311 else: 312 if hasattr(vs, "parent"): 313 yield k, vs 314 315 def find(self, *expression_types: t.Type[E], bfs=True) -> E | None: 316 """ 317 Returns the first node in this tree which matches at least one of 318 the specified types. 319 320 Args: 321 expression_types: the expression type(s) to match. 322 323 Returns: 324 The node which matches the criteria or None if no such node was found. 325 """ 326 return next(self.find_all(*expression_types, bfs=bfs), None) 327 328 def find_all(self, *expression_types: t.Type[E], bfs=True) -> t.Iterator[E]: 329 """ 330 Returns a generator object which visits all nodes in this tree and only 331 yields those that match at least one of the specified expression types. 332 333 Args: 334 expression_types: the expression type(s) to match. 335 336 Returns: 337 The generator object. 338 """ 339 for expression, *_ in self.walk(bfs=bfs): 340 if isinstance(expression, expression_types): 341 yield expression 342 343 def find_ancestor(self, *expression_types: t.Type[E]) -> E | None: 344 """ 345 Returns a nearest parent matching expression_types. 346 347 Args: 348 expression_types: the expression type(s) to match. 349 350 Returns: 351 The parent node. 352 """ 353 ancestor = self.parent 354 while ancestor and not isinstance(ancestor, expression_types): 355 ancestor = ancestor.parent 356 return t.cast(E, ancestor) 357 358 @property 359 def parent_select(self): 360 """ 361 Returns the parent select statement. 362 """ 363 return self.find_ancestor(Select) 364 365 @property 366 def same_parent(self): 367 """Returns if the parent is the same class as itself.""" 368 return type(self.parent) is self.__class__ 369 370 def root(self) -> Expression: 371 """ 372 Returns the root expression of this tree. 373 """ 374 expression = self 375 while expression.parent: 376 expression = expression.parent 377 return expression 378 379 def walk(self, bfs=True, prune=None): 380 """ 381 Returns a generator object which visits all nodes in this tree. 382 383 Args: 384 bfs (bool): if set to True the BFS traversal order will be applied, 385 otherwise the DFS traversal will be used instead. 386 prune ((node, parent, arg_key) -> bool): callable that returns True if 387 the generator should stop traversing this branch of the tree. 388 389 Returns: 390 the generator object. 391 """ 392 if bfs: 393 yield from self.bfs(prune=prune) 394 else: 395 yield from self.dfs(prune=prune) 396 397 def dfs(self, parent=None, key=None, prune=None): 398 """ 399 Returns a generator object which visits all nodes in this tree in 400 the DFS (Depth-first) order. 401 402 Returns: 403 The generator object. 404 """ 405 parent = parent or self.parent 406 yield self, parent, key 407 if prune and prune(self, parent, key): 408 return 409 410 for k, v in self.iter_expressions(): 411 yield from v.dfs(self, k, prune) 412 413 def bfs(self, prune=None): 414 """ 415 Returns a generator object which visits all nodes in this tree in 416 the BFS (Breadth-first) order. 417 418 Returns: 419 The generator object. 420 """ 421 queue = deque([(self, self.parent, None)]) 422 423 while queue: 424 item, parent, key = queue.popleft() 425 426 yield item, parent, key 427 if prune and prune(item, parent, key): 428 continue 429 430 for k, v in item.iter_expressions(): 431 queue.append((v, item, k)) 432 433 def unnest(self): 434 """ 435 Returns the first non parenthesis child or self. 436 """ 437 expression = self 438 while type(expression) is Paren: 439 expression = expression.this 440 return expression 441 442 def unalias(self): 443 """ 444 Returns the inner expression if this is an Alias. 445 """ 446 if isinstance(self, Alias): 447 return self.this 448 return self 449 450 def unnest_operands(self): 451 """ 452 Returns unnested operands as a tuple. 453 """ 454 return tuple(arg.unnest() for _, arg in self.iter_expressions()) 455 456 def flatten(self, unnest=True): 457 """ 458 Returns a generator which yields child nodes who's parents are the same class. 459 460 A AND B AND C -> [A, B, C] 461 """ 462 for node, _, _ in self.dfs(prune=lambda n, p, *_: p and not type(n) is self.__class__): 463 if not type(node) is self.__class__: 464 yield node.unnest() if unnest else node 465 466 def __str__(self): 467 return self.sql() 468 469 def __repr__(self): 470 return self._to_s() 471 472 def sql(self, dialect: DialectType = None, **opts) -> str: 473 """ 474 Returns SQL string representation of this tree. 475 476 Args: 477 dialect: the dialect of the output SQL string (eg. "spark", "hive", "presto", "mysql"). 478 opts: other `sqlglot.generator.Generator` options. 479 480 Returns: 481 The SQL string. 482 """ 483 from sqlglot.dialects import Dialect 484 485 return Dialect.get_or_raise(dialect)().generate(self, **opts) 486 487 def _to_s(self, hide_missing: bool = True, level: int = 0) -> str: 488 indent = "" if not level else "\n" 489 indent += "".join([" "] * level) 490 left = f"({self.key.upper()} " 491 492 args: t.Dict[str, t.Any] = { 493 k: ", ".join( 494 v._to_s(hide_missing=hide_missing, level=level + 1) 495 if hasattr(v, "_to_s") 496 else str(v) 497 for v in ensure_list(vs) 498 if v is not None 499 ) 500 for k, vs in self.args.items() 501 } 502 args["comments"] = self.comments 503 args["type"] = self.type 504 args = {k: v for k, v in args.items() if v or not hide_missing} 505 506 right = ", ".join(f"{k}: {v}" for k, v in args.items()) 507 right += ")" 508 509 return indent + left + right 510 511 def transform(self, fun, *args, copy=True, **kwargs): 512 """ 513 Recursively visits all tree nodes (excluding already transformed ones) 514 and applies the given transformation function to each node. 515 516 Args: 517 fun (function): a function which takes a node as an argument and returns a 518 new transformed node or the same node without modifications. If the function 519 returns None, then the corresponding node will be removed from the syntax tree. 520 copy (bool): if set to True a new tree instance is constructed, otherwise the tree is 521 modified in place. 522 523 Returns: 524 The transformed tree. 525 """ 526 node = self.copy() if copy else self 527 new_node = fun(node, *args, **kwargs) 528 529 if new_node is None or not isinstance(new_node, Expression): 530 return new_node 531 if new_node is not node: 532 new_node.parent = node.parent 533 return new_node 534 535 replace_children(new_node, lambda child: child.transform(fun, *args, copy=False, **kwargs)) 536 return new_node 537 538 def replace(self, expression): 539 """ 540 Swap out this expression with a new expression. 541 542 For example:: 543 544 >>> tree = Select().select("x").from_("tbl") 545 >>> tree.find(Column).replace(Column(this="y")) 546 (COLUMN this: y) 547 >>> tree.sql() 548 'SELECT y FROM tbl' 549 550 Args: 551 expression (Expression|None): new node 552 553 Returns: 554 The new expression or expressions. 555 """ 556 if not self.parent: 557 return expression 558 559 parent = self.parent 560 self.parent = None 561 562 replace_children(parent, lambda child: expression if child is self else child) 563 return expression 564 565 def pop(self): 566 """ 567 Remove this expression from its AST. 568 569 Returns: 570 The popped expression. 571 """ 572 self.replace(None) 573 return self 574 575 def assert_is(self, type_): 576 """ 577 Assert that this `Expression` is an instance of `type_`. 578 579 If it is NOT an instance of `type_`, this raises an assertion error. 580 Otherwise, this returns this expression. 581 582 Examples: 583 This is useful for type security in chained expressions: 584 585 >>> import sqlglot 586 >>> sqlglot.parse_one("SELECT x from y").assert_is(Select).select("z").sql() 587 'SELECT x, z FROM y' 588 """ 589 assert isinstance(self, type_) 590 return self 591 592 def error_messages(self, args: t.Optional[t.Sequence] = None) -> t.List[str]: 593 """ 594 Checks if this expression is valid (e.g. all mandatory args are set). 595 596 Args: 597 args: a sequence of values that were used to instantiate a Func expression. This is used 598 to check that the provided arguments don't exceed the function argument limit. 599 600 Returns: 601 A list of error messages for all possible errors that were found. 602 """ 603 errors: t.List[str] = [] 604 605 for k in self.args: 606 if k not in self.arg_types: 607 errors.append(f"Unexpected keyword: '{k}' for {self.__class__}") 608 for k, mandatory in self.arg_types.items(): 609 v = self.args.get(k) 610 if mandatory and (v is None or (isinstance(v, list) and not v)): 611 errors.append(f"Required keyword: '{k}' missing for {self.__class__}") 612 613 if ( 614 args 615 and isinstance(self, Func) 616 and len(args) > len(self.arg_types) 617 and not self.is_var_len_args 618 ): 619 errors.append( 620 f"The number of provided arguments ({len(args)}) is greater than " 621 f"the maximum number of supported arguments ({len(self.arg_types)})" 622 ) 623 624 return errors 625 626 def dump(self): 627 """ 628 Dump this Expression to a JSON-serializable dict. 629 """ 630 from sqlglot.serde import dump 631 632 return dump(self) 633 634 @classmethod 635 def load(cls, obj): 636 """ 637 Load a dict (as returned by `Expression.dump`) into an Expression instance. 638 """ 639 from sqlglot.serde import load 640 641 return load(obj) 642 643 644IntoType = t.Union[ 645 str, 646 t.Type[Expression], 647 t.Collection[t.Union[str, t.Type[Expression]]], 648] 649ExpOrStr = t.Union[str, Expression] 650 651 652class Condition(Expression): 653 def and_(self, *expressions, dialect=None, **opts): 654 """ 655 AND this condition with one or multiple expressions. 656 657 Example: 658 >>> condition("x=1").and_("y=1").sql() 659 'x = 1 AND y = 1' 660 661 Args: 662 *expressions (str | Expression): the SQL code strings to parse. 663 If an `Expression` instance is passed, it will be used as-is. 664 dialect (str): the dialect used to parse the input expression. 665 opts (kwargs): other options to use to parse the input expressions. 666 667 Returns: 668 And: the new condition. 669 """ 670 return and_(self, *expressions, dialect=dialect, **opts) 671 672 def or_(self, *expressions, dialect=None, **opts): 673 """ 674 OR this condition with one or multiple expressions. 675 676 Example: 677 >>> condition("x=1").or_("y=1").sql() 678 'x = 1 OR y = 1' 679 680 Args: 681 *expressions (str | Expression): the SQL code strings to parse. 682 If an `Expression` instance is passed, it will be used as-is. 683 dialect (str): the dialect used to parse the input expression. 684 opts (kwargs): other options to use to parse the input expressions. 685 686 Returns: 687 Or: the new condition. 688 """ 689 return or_(self, *expressions, dialect=dialect, **opts) 690 691 def not_(self): 692 """ 693 Wrap this condition with NOT. 694 695 Example: 696 >>> condition("x=1").not_().sql() 697 'NOT x = 1' 698 699 Returns: 700 Not: the new condition. 701 """ 702 return not_(self) 703 704 def _binop(self, klass: t.Type[E], other: ExpOrStr, reverse=False) -> E: 705 this = self 706 other = convert(other) 707 if not isinstance(this, klass) and not isinstance(other, klass): 708 this = _wrap(this, Binary) 709 other = _wrap(other, Binary) 710 if reverse: 711 return klass(this=other, expression=this) 712 return klass(this=this, expression=other) 713 714 def __getitem__(self, other: ExpOrStr | slice | t.Tuple[ExpOrStr]): 715 if isinstance(other, slice): 716 return Between( 717 this=self, 718 low=convert(other.start), 719 high=convert(other.stop), 720 ) 721 return Bracket(this=self, expressions=[convert(e) for e in ensure_list(other)]) 722 723 def isin(self, *expressions: ExpOrStr, query: t.Optional[ExpOrStr] = None, **opts) -> In: 724 return In( 725 this=self, 726 expressions=[convert(e) for e in expressions], 727 query=maybe_parse(query, **opts) if query else None, 728 ) 729 730 def like(self, other: ExpOrStr) -> Like: 731 return self._binop(Like, other) 732 733 def ilike(self, other: ExpOrStr) -> ILike: 734 return self._binop(ILike, other) 735 736 def eq(self, other: ExpOrStr) -> EQ: 737 return self._binop(EQ, other) 738 739 def neq(self, other: ExpOrStr) -> NEQ: 740 return self._binop(NEQ, other) 741 742 def rlike(self, other: ExpOrStr) -> RegexpLike: 743 return self._binop(RegexpLike, other) 744 745 def __lt__(self, other: ExpOrStr) -> LT: 746 return self._binop(LT, other) 747 748 def __le__(self, other: ExpOrStr) -> LTE: 749 return self._binop(LTE, other) 750 751 def __gt__(self, other: ExpOrStr) -> GT: 752 return self._binop(GT, other) 753 754 def __ge__(self, other: ExpOrStr) -> GTE: 755 return self._binop(GTE, other) 756 757 def __add__(self, other: ExpOrStr) -> Add: 758 return self._binop(Add, other) 759 760 def __radd__(self, other: ExpOrStr) -> Add: 761 return self._binop(Add, other, reverse=True) 762 763 def __sub__(self, other: ExpOrStr) -> Sub: 764 return self._binop(Sub, other) 765 766 def __rsub__(self, other: ExpOrStr) -> Sub: 767 return self._binop(Sub, other, reverse=True) 768 769 def __mul__(self, other: ExpOrStr) -> Mul: 770 return self._binop(Mul, other) 771 772 def __rmul__(self, other: ExpOrStr) -> Mul: 773 return self._binop(Mul, other, reverse=True) 774 775 def __truediv__(self, other: ExpOrStr) -> Div: 776 return self._binop(Div, other) 777 778 def __rtruediv__(self, other: ExpOrStr) -> Div: 779 return self._binop(Div, other, reverse=True) 780 781 def __floordiv__(self, other: ExpOrStr) -> IntDiv: 782 return self._binop(IntDiv, other) 783 784 def __rfloordiv__(self, other: ExpOrStr) -> IntDiv: 785 return self._binop(IntDiv, other, reverse=True) 786 787 def __mod__(self, other: ExpOrStr) -> Mod: 788 return self._binop(Mod, other) 789 790 def __rmod__(self, other: ExpOrStr) -> Mod: 791 return self._binop(Mod, other, reverse=True) 792 793 def __pow__(self, other: ExpOrStr) -> Pow: 794 return self._binop(Pow, other) 795 796 def __rpow__(self, other: ExpOrStr) -> Pow: 797 return self._binop(Pow, other, reverse=True) 798 799 def __and__(self, other: ExpOrStr) -> And: 800 return self._binop(And, other) 801 802 def __rand__(self, other: ExpOrStr) -> And: 803 return self._binop(And, other, reverse=True) 804 805 def __or__(self, other: ExpOrStr) -> Or: 806 return self._binop(Or, other) 807 808 def __ror__(self, other: ExpOrStr) -> Or: 809 return self._binop(Or, other, reverse=True) 810 811 def __neg__(self) -> Neg: 812 return Neg(this=_wrap(self, Binary)) 813 814 def __invert__(self) -> Not: 815 return not_(self) 816 817 818class Predicate(Condition): 819 """Relationships like x = y, x > 1, x >= y.""" 820 821 822class DerivedTable(Expression): 823 @property 824 def alias_column_names(self): 825 table_alias = self.args.get("alias") 826 if not table_alias: 827 return [] 828 column_list = table_alias.assert_is(TableAlias).args.get("columns") or [] 829 return [c.name for c in column_list] 830 831 @property 832 def selects(self): 833 alias = self.args.get("alias") 834 835 if alias: 836 return alias.columns 837 return [] 838 839 @property 840 def named_selects(self): 841 return [select.output_name for select in self.selects] 842 843 844class Unionable(Expression): 845 def union(self, expression, distinct=True, dialect=None, **opts): 846 """ 847 Builds a UNION expression. 848 849 Example: 850 >>> import sqlglot 851 >>> sqlglot.parse_one("SELECT * FROM foo").union("SELECT * FROM bla").sql() 852 'SELECT * FROM foo UNION SELECT * FROM bla' 853 854 Args: 855 expression (str | Expression): the SQL code string. 856 If an `Expression` instance is passed, it will be used as-is. 857 distinct (bool): set the DISTINCT flag if and only if this is true. 858 dialect (str): the dialect used to parse the input expression. 859 opts (kwargs): other options to use to parse the input expressions. 860 Returns: 861 Union: the Union expression. 862 """ 863 return union(left=self, right=expression, distinct=distinct, dialect=dialect, **opts) 864 865 def intersect(self, expression, distinct=True, dialect=None, **opts): 866 """ 867 Builds an INTERSECT expression. 868 869 Example: 870 >>> import sqlglot 871 >>> sqlglot.parse_one("SELECT * FROM foo").intersect("SELECT * FROM bla").sql() 872 'SELECT * FROM foo INTERSECT SELECT * FROM bla' 873 874 Args: 875 expression (str | Expression): the SQL code string. 876 If an `Expression` instance is passed, it will be used as-is. 877 distinct (bool): set the DISTINCT flag if and only if this is true. 878 dialect (str): the dialect used to parse the input expression. 879 opts (kwargs): other options to use to parse the input expressions. 880 Returns: 881 Intersect: the Intersect expression 882 """ 883 return intersect(left=self, right=expression, distinct=distinct, dialect=dialect, **opts) 884 885 def except_(self, expression, distinct=True, dialect=None, **opts): 886 """ 887 Builds an EXCEPT expression. 888 889 Example: 890 >>> import sqlglot 891 >>> sqlglot.parse_one("SELECT * FROM foo").except_("SELECT * FROM bla").sql() 892 'SELECT * FROM foo EXCEPT SELECT * FROM bla' 893 894 Args: 895 expression (str | Expression): the SQL code string. 896 If an `Expression` instance is passed, it will be used as-is. 897 distinct (bool): set the DISTINCT flag if and only if this is true. 898 dialect (str): the dialect used to parse the input expression. 899 opts (kwargs): other options to use to parse the input expressions. 900 Returns: 901 Except: the Except expression 902 """ 903 return except_(left=self, right=expression, distinct=distinct, dialect=dialect, **opts) 904 905 906class UDTF(DerivedTable, Unionable): 907 pass 908 909 910class Cache(Expression): 911 arg_types = { 912 "with": False, 913 "this": True, 914 "lazy": False, 915 "options": False, 916 "expression": False, 917 } 918 919 920class Uncache(Expression): 921 arg_types = {"this": True, "exists": False} 922 923 924class Create(Expression): 925 arg_types = { 926 "with": False, 927 "this": True, 928 "kind": True, 929 "expression": False, 930 "exists": False, 931 "properties": False, 932 "replace": False, 933 "unique": False, 934 "indexes": False, 935 "no_schema_binding": False, 936 "begin": False, 937 } 938 939 940class Describe(Expression): 941 arg_types = {"this": True, "kind": False} 942 943 944class Pragma(Expression): 945 pass 946 947 948class Set(Expression): 949 arg_types = {"expressions": False} 950 951 952class SetItem(Expression): 953 arg_types = { 954 "this": False, 955 "expressions": False, 956 "kind": False, 957 "collate": False, # MySQL SET NAMES statement 958 "global": False, 959 } 960 961 962class Show(Expression): 963 arg_types = { 964 "this": True, 965 "target": False, 966 "offset": False, 967 "limit": False, 968 "like": False, 969 "where": False, 970 "db": False, 971 "full": False, 972 "mutex": False, 973 "query": False, 974 "channel": False, 975 "global": False, 976 "log": False, 977 "position": False, 978 "types": False, 979 } 980 981 982class UserDefinedFunction(Expression): 983 arg_types = {"this": True, "expressions": False, "wrapped": False} 984 985 986class CharacterSet(Expression): 987 arg_types = {"this": True, "default": False} 988 989 990class With(Expression): 991 arg_types = {"expressions": True, "recursive": False} 992 993 @property 994 def recursive(self) -> bool: 995 return bool(self.args.get("recursive")) 996 997 998class WithinGroup(Expression): 999 arg_types = {"this": True, "expression": False} 1000 1001 1002class CTE(DerivedTable): 1003 arg_types = {"this": True, "alias": True} 1004 1005 1006class TableAlias(Expression): 1007 arg_types = {"this": False, "columns": False} 1008 1009 @property 1010 def columns(self): 1011 return self.args.get("columns") or [] 1012 1013 1014class BitString(Condition): 1015 pass 1016 1017 1018class HexString(Condition): 1019 pass 1020 1021 1022class ByteString(Condition): 1023 pass 1024 1025 1026class Column(Condition): 1027 arg_types = {"this": True, "table": False, "db": False, "catalog": False, "join_mark": False} 1028 1029 @property 1030 def table(self) -> str: 1031 return self.text("table") 1032 1033 @property 1034 def db(self) -> str: 1035 return self.text("db") 1036 1037 @property 1038 def catalog(self) -> str: 1039 return self.text("catalog") 1040 1041 @property 1042 def output_name(self) -> str: 1043 return self.name 1044 1045 @property 1046 def parts(self) -> t.List[Identifier]: 1047 """Return the parts of a column in order catalog, db, table, name.""" 1048 return [part for part in reversed(list(self.args.values())) if part] 1049 1050 def to_dot(self) -> Dot: 1051 """Converts the column into a dot expression.""" 1052 parts = self.parts 1053 parent = self.parent 1054 1055 while parent: 1056 if isinstance(parent, Dot): 1057 parts.append(parent.expression) 1058 parent = parent.parent 1059 1060 return Dot.build(parts) 1061 1062 1063class ColumnPosition(Expression): 1064 arg_types = {"this": False, "position": True} 1065 1066 1067class ColumnDef(Expression): 1068 arg_types = { 1069 "this": True, 1070 "kind": False, 1071 "constraints": False, 1072 "exists": False, 1073 "position": False, 1074 } 1075 1076 1077class AlterColumn(Expression): 1078 arg_types = { 1079 "this": True, 1080 "dtype": False, 1081 "collate": False, 1082 "using": False, 1083 "default": False, 1084 "drop": False, 1085 } 1086 1087 1088class RenameTable(Expression): 1089 pass 1090 1091 1092class SetTag(Expression): 1093 arg_types = {"expressions": True, "unset": False} 1094 1095 1096class Comment(Expression): 1097 arg_types = {"this": True, "kind": True, "expression": True, "exists": False} 1098 1099 1100class ColumnConstraint(Expression): 1101 arg_types = {"this": False, "kind": True} 1102 1103 1104class ColumnConstraintKind(Expression): 1105 pass 1106 1107 1108class AutoIncrementColumnConstraint(ColumnConstraintKind): 1109 pass 1110 1111 1112class CaseSpecificColumnConstraint(ColumnConstraintKind): 1113 arg_types = {"not_": True} 1114 1115 1116class CharacterSetColumnConstraint(ColumnConstraintKind): 1117 arg_types = {"this": True} 1118 1119 1120class CheckColumnConstraint(ColumnConstraintKind): 1121 pass 1122 1123 1124class CollateColumnConstraint(ColumnConstraintKind): 1125 pass 1126 1127 1128class CommentColumnConstraint(ColumnConstraintKind): 1129 pass 1130 1131 1132class CompressColumnConstraint(ColumnConstraintKind): 1133 pass 1134 1135 1136class DateFormatColumnConstraint(ColumnConstraintKind): 1137 arg_types = {"this": True} 1138 1139 1140class DefaultColumnConstraint(ColumnConstraintKind): 1141 pass 1142 1143 1144class EncodeColumnConstraint(ColumnConstraintKind): 1145 pass 1146 1147 1148class GeneratedAsIdentityColumnConstraint(ColumnConstraintKind): 1149 # this: True -> ALWAYS, this: False -> BY DEFAULT 1150 arg_types = { 1151 "this": False, 1152 "start": False, 1153 "increment": False, 1154 "minvalue": False, 1155 "maxvalue": False, 1156 "cycle": False, 1157 } 1158 1159 1160class InlineLengthColumnConstraint(ColumnConstraintKind): 1161 pass 1162 1163 1164class NotNullColumnConstraint(ColumnConstraintKind): 1165 arg_types = {"allow_null": False} 1166 1167 1168# https://dev.mysql.com/doc/refman/5.7/en/timestamp-initialization.html 1169class OnUpdateColumnConstraint(ColumnConstraintKind): 1170 pass 1171 1172 1173class PrimaryKeyColumnConstraint(ColumnConstraintKind): 1174 arg_types = {"desc": False} 1175 1176 1177class TitleColumnConstraint(ColumnConstraintKind): 1178 pass 1179 1180 1181class UniqueColumnConstraint(ColumnConstraintKind): 1182 arg_types: t.Dict[str, t.Any] = {} 1183 1184 1185class UppercaseColumnConstraint(ColumnConstraintKind): 1186 arg_types: t.Dict[str, t.Any] = {} 1187 1188 1189class PathColumnConstraint(ColumnConstraintKind): 1190 pass 1191 1192 1193class Constraint(Expression): 1194 arg_types = {"this": True, "expressions": True} 1195 1196 1197class Delete(Expression): 1198 arg_types = {"with": False, "this": False, "using": False, "where": False, "returning": False} 1199 1200 def delete( 1201 self, 1202 table: ExpOrStr, 1203 dialect: DialectType = None, 1204 copy: bool = True, 1205 **opts, 1206 ) -> Delete: 1207 """ 1208 Create a DELETE expression or replace the table on an existing DELETE expression. 1209 1210 Example: 1211 >>> delete("tbl").sql() 1212 'DELETE FROM tbl' 1213 1214 Args: 1215 table: the table from which to delete. 1216 dialect: the dialect used to parse the input expression. 1217 copy: if `False`, modify this expression instance in-place. 1218 opts: other options to use to parse the input expressions. 1219 1220 Returns: 1221 Delete: the modified expression. 1222 """ 1223 return _apply_builder( 1224 expression=table, 1225 instance=self, 1226 arg="this", 1227 dialect=dialect, 1228 into=Table, 1229 copy=copy, 1230 **opts, 1231 ) 1232 1233 def where( 1234 self, 1235 *expressions: ExpOrStr, 1236 append: bool = True, 1237 dialect: DialectType = None, 1238 copy: bool = True, 1239 **opts, 1240 ) -> Delete: 1241 """ 1242 Append to or set the WHERE expressions. 1243 1244 Example: 1245 >>> delete("tbl").where("x = 'a' OR x < 'b'").sql() 1246 "DELETE FROM tbl WHERE x = 'a' OR x < 'b'" 1247 1248 Args: 1249 *expressions: the SQL code strings to parse. 1250 If an `Expression` instance is passed, it will be used as-is. 1251 Multiple expressions are combined with an AND operator. 1252 append: if `True`, AND the new expressions to any existing expression. 1253 Otherwise, this resets the expression. 1254 dialect: the dialect used to parse the input expressions. 1255 copy: if `False`, modify this expression instance in-place. 1256 opts: other options to use to parse the input expressions. 1257 1258 Returns: 1259 Delete: the modified expression. 1260 """ 1261 return _apply_conjunction_builder( 1262 *expressions, 1263 instance=self, 1264 arg="where", 1265 append=append, 1266 into=Where, 1267 dialect=dialect, 1268 copy=copy, 1269 **opts, 1270 ) 1271 1272 def returning( 1273 self, 1274 expression: ExpOrStr, 1275 dialect: DialectType = None, 1276 copy: bool = True, 1277 **opts, 1278 ) -> Delete: 1279 """ 1280 Set the RETURNING expression. Not supported by all dialects. 1281 1282 Example: 1283 >>> delete("tbl").returning("*", dialect="postgres").sql() 1284 'DELETE FROM tbl RETURNING *' 1285 1286 Args: 1287 expression: the SQL code strings to parse. 1288 If an `Expression` instance is passed, it will be used as-is. 1289 dialect: the dialect used to parse the input expressions. 1290 copy: if `False`, modify this expression instance in-place. 1291 opts: other options to use to parse the input expressions. 1292 1293 Returns: 1294 Delete: the modified expression. 1295 """ 1296 return _apply_builder( 1297 expression=expression, 1298 instance=self, 1299 arg="returning", 1300 prefix="RETURNING", 1301 dialect=dialect, 1302 copy=copy, 1303 into=Returning, 1304 **opts, 1305 ) 1306 1307 1308class Drop(Expression): 1309 arg_types = { 1310 "this": False, 1311 "kind": False, 1312 "exists": False, 1313 "temporary": False, 1314 "materialized": False, 1315 "cascade": False, 1316 "constraints": False, 1317 "purge": False, 1318 } 1319 1320 1321class Filter(Expression): 1322 arg_types = {"this": True, "expression": True} 1323 1324 1325class Check(Expression): 1326 pass 1327 1328 1329class Directory(Expression): 1330 # https://spark.apache.org/docs/3.0.0-preview/sql-ref-syntax-dml-insert-overwrite-directory-hive.html 1331 arg_types = {"this": True, "local": False, "row_format": False} 1332 1333 1334class ForeignKey(Expression): 1335 arg_types = { 1336 "expressions": True, 1337 "reference": False, 1338 "delete": False, 1339 "update": False, 1340 } 1341 1342 1343class PrimaryKey(Expression): 1344 arg_types = {"expressions": True, "options": False} 1345 1346 1347class Unique(Expression): 1348 arg_types = {"expressions": True} 1349 1350 1351# https://www.postgresql.org/docs/9.1/sql-selectinto.html 1352# https://docs.aws.amazon.com/redshift/latest/dg/r_SELECT_INTO.html#r_SELECT_INTO-examples 1353class Into(Expression): 1354 arg_types = {"this": True, "temporary": False, "unlogged": False} 1355 1356 1357class From(Expression): 1358 arg_types = {"expressions": True} 1359 1360 1361class Having(Expression): 1362 pass 1363 1364 1365class Hint(Expression): 1366 arg_types = {"expressions": True} 1367 1368 1369class JoinHint(Expression): 1370 arg_types = {"this": True, "expressions": True} 1371 1372 1373class Identifier(Expression): 1374 arg_types = {"this": True, "quoted": False} 1375 1376 @property 1377 def quoted(self): 1378 return bool(self.args.get("quoted")) 1379 1380 @property 1381 def hashable_args(self) -> t.Any: 1382 if self.quoted and any(char.isupper() for char in self.this): 1383 return (self.this, self.quoted) 1384 return self.this.lower() 1385 1386 @property 1387 def output_name(self): 1388 return self.name 1389 1390 1391class Index(Expression): 1392 arg_types = { 1393 "this": False, 1394 "table": False, 1395 "where": False, 1396 "columns": False, 1397 "unique": False, 1398 "primary": False, 1399 "amp": False, # teradata 1400 } 1401 1402 1403class Insert(Expression): 1404 arg_types = { 1405 "with": False, 1406 "this": True, 1407 "expression": False, 1408 "conflict": False, 1409 "returning": False, 1410 "overwrite": False, 1411 "exists": False, 1412 "partition": False, 1413 "alternative": False, 1414 } 1415 1416 1417class OnConflict(Expression): 1418 arg_types = { 1419 "duplicate": False, 1420 "expressions": False, 1421 "nothing": False, 1422 "key": False, 1423 "constraint": False, 1424 } 1425 1426 1427class Returning(Expression): 1428 arg_types = {"expressions": True} 1429 1430 1431# https://dev.mysql.com/doc/refman/8.0/en/charset-introducer.html 1432class Introducer(Expression): 1433 arg_types = {"this": True, "expression": True} 1434 1435 1436# national char, like n'utf8' 1437class National(Expression): 1438 pass 1439 1440 1441class LoadData(Expression): 1442 arg_types = { 1443 "this": True, 1444 "local": False, 1445 "overwrite": False, 1446 "inpath": True, 1447 "partition": False, 1448 "input_format": False, 1449 "serde": False, 1450 } 1451 1452 1453class Partition(Expression): 1454 arg_types = {"expressions": True} 1455 1456 1457class Fetch(Expression): 1458 arg_types = { 1459 "direction": False, 1460 "count": False, 1461 "percent": False, 1462 "with_ties": False, 1463 } 1464 1465 1466class Group(Expression): 1467 arg_types = { 1468 "expressions": False, 1469 "grouping_sets": False, 1470 "cube": False, 1471 "rollup": False, 1472 } 1473 1474 1475class Lambda(Expression): 1476 arg_types = {"this": True, "expressions": True} 1477 1478 1479class Limit(Expression): 1480 arg_types = {"this": False, "expression": True} 1481 1482 1483class Literal(Condition): 1484 arg_types = {"this": True, "is_string": True} 1485 1486 @property 1487 def hashable_args(self) -> t.Any: 1488 return (self.this, self.args.get("is_string")) 1489 1490 @classmethod 1491 def number(cls, number) -> Literal: 1492 return cls(this=str(number), is_string=False) 1493 1494 @classmethod 1495 def string(cls, string) -> Literal: 1496 return cls(this=str(string), is_string=True) 1497 1498 @property 1499 def output_name(self): 1500 return self.name 1501 1502 1503class Join(Expression): 1504 arg_types = { 1505 "this": True, 1506 "on": False, 1507 "side": False, 1508 "kind": False, 1509 "using": False, 1510 "natural": False, 1511 "hint": False, 1512 } 1513 1514 @property 1515 def kind(self): 1516 return self.text("kind").upper() 1517 1518 @property 1519 def side(self): 1520 return self.text("side").upper() 1521 1522 @property 1523 def hint(self): 1524 return self.text("hint").upper() 1525 1526 @property 1527 def alias_or_name(self): 1528 return self.this.alias_or_name 1529 1530 def on(self, *expressions, append=True, dialect=None, copy=True, **opts): 1531 """ 1532 Append to or set the ON expressions. 1533 1534 Example: 1535 >>> import sqlglot 1536 >>> sqlglot.parse_one("JOIN x", into=Join).on("y = 1").sql() 1537 'JOIN x ON y = 1' 1538 1539 Args: 1540 *expressions (str | Expression): the SQL code strings to parse. 1541 If an `Expression` instance is passed, it will be used as-is. 1542 Multiple expressions are combined with an AND operator. 1543 append (bool): if `True`, AND the new expressions to any existing expression. 1544 Otherwise, this resets the expression. 1545 dialect (str): the dialect used to parse the input expressions. 1546 copy (bool): if `False`, modify this expression instance in-place. 1547 opts (kwargs): other options to use to parse the input expressions. 1548 1549 Returns: 1550 Join: the modified join expression. 1551 """ 1552 join = _apply_conjunction_builder( 1553 *expressions, 1554 instance=self, 1555 arg="on", 1556 append=append, 1557 dialect=dialect, 1558 copy=copy, 1559 **opts, 1560 ) 1561 1562 if join.kind == "CROSS": 1563 join.set("kind", None) 1564 1565 return join 1566 1567 def using(self, *expressions, append=True, dialect=None, copy=True, **opts): 1568 """ 1569 Append to or set the USING expressions. 1570 1571 Example: 1572 >>> import sqlglot 1573 >>> sqlglot.parse_one("JOIN x", into=Join).using("foo", "bla").sql() 1574 'JOIN x USING (foo, bla)' 1575 1576 Args: 1577 *expressions (str | Expression): the SQL code strings to parse. 1578 If an `Expression` instance is passed, it will be used as-is. 1579 append (bool): if `True`, concatenate the new expressions to the existing "using" list. 1580 Otherwise, this resets the expression. 1581 dialect (str): the dialect used to parse the input expressions. 1582 copy (bool): if `False`, modify this expression instance in-place. 1583 opts (kwargs): other options to use to parse the input expressions. 1584 1585 Returns: 1586 Join: the modified join expression. 1587 """ 1588 join = _apply_list_builder( 1589 *expressions, 1590 instance=self, 1591 arg="using", 1592 append=append, 1593 dialect=dialect, 1594 copy=copy, 1595 **opts, 1596 ) 1597 1598 if join.kind == "CROSS": 1599 join.set("kind", None) 1600 1601 return join 1602 1603 1604class Lateral(UDTF): 1605 arg_types = {"this": True, "view": False, "outer": False, "alias": False} 1606 1607 1608class MatchRecognize(Expression): 1609 arg_types = { 1610 "partition_by": False, 1611 "order": False, 1612 "measures": False, 1613 "rows": False, 1614 "after": False, 1615 "pattern": False, 1616 "define": False, 1617 "alias": False, 1618 } 1619 1620 1621# Clickhouse FROM FINAL modifier 1622# https://clickhouse.com/docs/en/sql-reference/statements/select/from/#final-modifier 1623class Final(Expression): 1624 pass 1625 1626 1627class Offset(Expression): 1628 arg_types = {"this": False, "expression": True} 1629 1630 1631class Order(Expression): 1632 arg_types = {"this": False, "expressions": True} 1633 1634 1635# hive specific sorts 1636# https://cwiki.apache.org/confluence/display/Hive/LanguageManual+SortBy 1637class Cluster(Order): 1638 pass 1639 1640 1641class Distribute(Order): 1642 pass 1643 1644 1645class Sort(Order): 1646 pass 1647 1648 1649class Ordered(Expression): 1650 arg_types = {"this": True, "desc": True, "nulls_first": True} 1651 1652 1653class Property(Expression): 1654 arg_types = {"this": True, "value": True} 1655 1656 1657class AfterJournalProperty(Property): 1658 arg_types = {"no": True, "dual": False, "local": False} 1659 1660 1661class AlgorithmProperty(Property): 1662 arg_types = {"this": True} 1663 1664 1665class AutoIncrementProperty(Property): 1666 arg_types = {"this": True} 1667 1668 1669class BlockCompressionProperty(Property): 1670 arg_types = {"autotemp": False, "always": False, "default": True, "manual": True, "never": True} 1671 1672 1673class CharacterSetProperty(Property): 1674 arg_types = {"this": True, "default": True} 1675 1676 1677class ChecksumProperty(Property): 1678 arg_types = {"on": False, "default": False} 1679 1680 1681class CollateProperty(Property): 1682 arg_types = {"this": True} 1683 1684 1685class DataBlocksizeProperty(Property): 1686 arg_types = {"size": False, "units": False, "min": False, "default": False} 1687 1688 1689class DefinerProperty(Property): 1690 arg_types = {"this": True} 1691 1692 1693class DistKeyProperty(Property): 1694 arg_types = {"this": True} 1695 1696 1697class DistStyleProperty(Property): 1698 arg_types = {"this": True} 1699 1700 1701class EngineProperty(Property): 1702 arg_types = {"this": True} 1703 1704 1705class ExecuteAsProperty(Property): 1706 arg_types = {"this": True} 1707 1708 1709class ExternalProperty(Property): 1710 arg_types = {"this": False} 1711 1712 1713class FallbackProperty(Property): 1714 arg_types = {"no": True, "protection": False} 1715 1716 1717class FileFormatProperty(Property): 1718 arg_types = {"this": True} 1719 1720 1721class FreespaceProperty(Property): 1722 arg_types = {"this": True, "percent": False} 1723 1724 1725class InputOutputFormat(Expression): 1726 arg_types = {"input_format": False, "output_format": False} 1727 1728 1729class IsolatedLoadingProperty(Property): 1730 arg_types = { 1731 "no": True, 1732 "concurrent": True, 1733 "for_all": True, 1734 "for_insert": True, 1735 "for_none": True, 1736 } 1737 1738 1739class JournalProperty(Property): 1740 arg_types = {"no": True, "dual": False, "before": False} 1741 1742 1743class LanguageProperty(Property): 1744 arg_types = {"this": True} 1745 1746 1747class LikeProperty(Property): 1748 arg_types = {"this": True, "expressions": False} 1749 1750 1751class LocationProperty(Property): 1752 arg_types = {"this": True} 1753 1754 1755class LockingProperty(Property): 1756 arg_types = { 1757 "this": False, 1758 "kind": True, 1759 "for_or_in": True, 1760 "lock_type": True, 1761 "override": False, 1762 } 1763 1764 1765class LogProperty(Property): 1766 arg_types = {"no": True} 1767 1768 1769class MaterializedProperty(Property): 1770 arg_types = {"this": False} 1771 1772 1773class MergeBlockRatioProperty(Property): 1774 arg_types = {"this": False, "no": False, "default": False, "percent": False} 1775 1776 1777class NoPrimaryIndexProperty(Property): 1778 arg_types = {"this": False} 1779 1780 1781class OnCommitProperty(Property): 1782 arg_type = {"this": False} 1783 1784 1785class PartitionedByProperty(Property): 1786 arg_types = {"this": True} 1787 1788 1789class ReturnsProperty(Property): 1790 arg_types = {"this": True, "is_table": False, "table": False} 1791 1792 1793class RowFormatProperty(Property): 1794 arg_types = {"this": True} 1795 1796 1797class RowFormatDelimitedProperty(Property): 1798 # https://cwiki.apache.org/confluence/display/hive/languagemanual+dml 1799 arg_types = { 1800 "fields": False, 1801 "escaped": False, 1802 "collection_items": False, 1803 "map_keys": False, 1804 "lines": False, 1805 "null": False, 1806 "serde": False, 1807 } 1808 1809 1810class RowFormatSerdeProperty(Property): 1811 arg_types = {"this": True} 1812 1813 1814class SchemaCommentProperty(Property): 1815 arg_types = {"this": True} 1816 1817 1818class SerdeProperties(Property): 1819 arg_types = {"expressions": True} 1820 1821 1822class SetProperty(Property): 1823 arg_types = {"multi": True} 1824 1825 1826class SortKeyProperty(Property): 1827 arg_types = {"this": True, "compound": False} 1828 1829 1830class SqlSecurityProperty(Property): 1831 arg_types = {"definer": True} 1832 1833 1834class StabilityProperty(Property): 1835 arg_types = {"this": True} 1836 1837 1838class TableFormatProperty(Property): 1839 arg_types = {"this": True} 1840 1841 1842class TemporaryProperty(Property): 1843 arg_types = {"global_": True} 1844 1845 1846class TransientProperty(Property): 1847 arg_types = {"this": False} 1848 1849 1850class VolatileProperty(Property): 1851 arg_types = {"this": False} 1852 1853 1854class WithDataProperty(Property): 1855 arg_types = {"no": True, "statistics": False} 1856 1857 1858class WithJournalTableProperty(Property): 1859 arg_types = {"this": True} 1860 1861 1862class Properties(Expression): 1863 arg_types = {"expressions": True} 1864 1865 NAME_TO_PROPERTY = { 1866 "ALGORITHM": AlgorithmProperty, 1867 "AUTO_INCREMENT": AutoIncrementProperty, 1868 "CHARACTER SET": CharacterSetProperty, 1869 "COLLATE": CollateProperty, 1870 "COMMENT": SchemaCommentProperty, 1871 "DEFINER": DefinerProperty, 1872 "DISTKEY": DistKeyProperty, 1873 "DISTSTYLE": DistStyleProperty, 1874 "ENGINE": EngineProperty, 1875 "EXECUTE AS": ExecuteAsProperty, 1876 "FORMAT": FileFormatProperty, 1877 "LANGUAGE": LanguageProperty, 1878 "LOCATION": LocationProperty, 1879 "PARTITIONED_BY": PartitionedByProperty, 1880 "RETURNS": ReturnsProperty, 1881 "ROW_FORMAT": RowFormatProperty, 1882 "SORTKEY": SortKeyProperty, 1883 "TABLE_FORMAT": TableFormatProperty, 1884 } 1885 1886 PROPERTY_TO_NAME = {v: k for k, v in NAME_TO_PROPERTY.items()} 1887 1888 # CREATE property locations 1889 # Form: schema specified 1890 # create [POST_CREATE] 1891 # table a [POST_NAME] 1892 # (b int) [POST_SCHEMA] 1893 # with ([POST_WITH]) 1894 # index (b) [POST_INDEX] 1895 # 1896 # Form: alias selection 1897 # create [POST_CREATE] 1898 # table a [POST_NAME] 1899 # as [POST_ALIAS] (select * from b) [POST_EXPRESSION] 1900 # index (c) [POST_INDEX] 1901 class Location(AutoName): 1902 POST_CREATE = auto() 1903 POST_NAME = auto() 1904 POST_SCHEMA = auto() 1905 POST_WITH = auto() 1906 POST_ALIAS = auto() 1907 POST_EXPRESSION = auto() 1908 POST_INDEX = auto() 1909 UNSUPPORTED = auto() 1910 1911 @classmethod 1912 def from_dict(cls, properties_dict) -> Properties: 1913 expressions = [] 1914 for key, value in properties_dict.items(): 1915 property_cls = cls.NAME_TO_PROPERTY.get(key.upper()) 1916 if property_cls: 1917 expressions.append(property_cls(this=convert(value))) 1918 else: 1919 expressions.append(Property(this=Literal.string(key), value=convert(value))) 1920 1921 return cls(expressions=expressions) 1922 1923 1924class Qualify(Expression): 1925 pass 1926 1927 1928# https://www.ibm.com/docs/en/ias?topic=procedures-return-statement-in-sql 1929class Return(Expression): 1930 pass 1931 1932 1933class Reference(Expression): 1934 arg_types = {"this": True, "expressions": False, "options": False} 1935 1936 1937class Tuple(Expression): 1938 arg_types = {"expressions": False} 1939 1940 1941class Subqueryable(Unionable): 1942 def subquery(self, alias=None, copy=True) -> Subquery: 1943 """ 1944 Convert this expression to an aliased expression that can be used as a Subquery. 1945 1946 Example: 1947 >>> subquery = Select().select("x").from_("tbl").subquery() 1948 >>> Select().select("x").from_(subquery).sql() 1949 'SELECT x FROM (SELECT x FROM tbl)' 1950 1951 Args: 1952 alias (str | Identifier): an optional alias for the subquery 1953 copy (bool): if `False`, modify this expression instance in-place. 1954 1955 Returns: 1956 Alias: the subquery 1957 """ 1958 instance = _maybe_copy(self, copy) 1959 return Subquery( 1960 this=instance, 1961 alias=TableAlias(this=to_identifier(alias)) if alias else None, 1962 ) 1963 1964 def limit(self, expression, dialect=None, copy=True, **opts) -> Select: 1965 raise NotImplementedError 1966 1967 @property 1968 def ctes(self): 1969 with_ = self.args.get("with") 1970 if not with_: 1971 return [] 1972 return with_.expressions 1973 1974 @property 1975 def selects(self): 1976 raise NotImplementedError("Subqueryable objects must implement `selects`") 1977 1978 @property 1979 def named_selects(self): 1980 raise NotImplementedError("Subqueryable objects must implement `named_selects`") 1981 1982 def with_( 1983 self, 1984 alias, 1985 as_, 1986 recursive=None, 1987 append=True, 1988 dialect=None, 1989 copy=True, 1990 **opts, 1991 ): 1992 """ 1993 Append to or set the common table expressions. 1994 1995 Example: 1996 >>> Select().with_("tbl2", as_="SELECT * FROM tbl").select("x").from_("tbl2").sql() 1997 'WITH tbl2 AS (SELECT * FROM tbl) SELECT x FROM tbl2' 1998 1999 Args: 2000 alias (str | Expression): the SQL code string to parse as the table name. 2001 If an `Expression` instance is passed, this is used as-is. 2002 as_ (str | Expression): the SQL code string to parse as the table expression. 2003 If an `Expression` instance is passed, it will be used as-is. 2004 recursive (bool): set the RECURSIVE part of the expression. Defaults to `False`. 2005 append (bool): if `True`, add to any existing expressions. 2006 Otherwise, this resets the expressions. 2007 dialect (str): the dialect used to parse the input expression. 2008 copy (bool): if `False`, modify this expression instance in-place. 2009 opts (kwargs): other options to use to parse the input expressions. 2010 2011 Returns: 2012 Select: the modified expression. 2013 """ 2014 alias_expression = maybe_parse( 2015 alias, 2016 dialect=dialect, 2017 into=TableAlias, 2018 **opts, 2019 ) 2020 as_expression = maybe_parse( 2021 as_, 2022 dialect=dialect, 2023 **opts, 2024 ) 2025 cte = CTE( 2026 this=as_expression, 2027 alias=alias_expression, 2028 ) 2029 return _apply_child_list_builder( 2030 cte, 2031 instance=self, 2032 arg="with", 2033 append=append, 2034 copy=copy, 2035 into=With, 2036 properties={"recursive": recursive or False}, 2037 ) 2038 2039 2040QUERY_MODIFIERS = { 2041 "match": False, 2042 "laterals": False, 2043 "joins": False, 2044 "pivots": False, 2045 "where": False, 2046 "group": False, 2047 "having": False, 2048 "qualify": False, 2049 "windows": False, 2050 "distribute": False, 2051 "sort": False, 2052 "cluster": False, 2053 "order": False, 2054 "limit": False, 2055 "offset": False, 2056 "lock": False, 2057 "sample": False, 2058} 2059 2060 2061class Table(Expression): 2062 arg_types = { 2063 "this": True, 2064 "alias": False, 2065 "db": False, 2066 "catalog": False, 2067 "laterals": False, 2068 "joins": False, 2069 "pivots": False, 2070 "hints": False, 2071 "system_time": False, 2072 } 2073 2074 @property 2075 def db(self) -> str: 2076 return self.text("db") 2077 2078 @property 2079 def catalog(self) -> str: 2080 return self.text("catalog") 2081 2082 2083# See the TSQL "Querying data in a system-versioned temporal table" page 2084class SystemTime(Expression): 2085 arg_types = { 2086 "this": False, 2087 "expression": False, 2088 "kind": True, 2089 } 2090 2091 2092class Union(Subqueryable): 2093 arg_types = { 2094 "with": False, 2095 "this": True, 2096 "expression": True, 2097 "distinct": False, 2098 **QUERY_MODIFIERS, 2099 } 2100 2101 def limit(self, expression, dialect=None, copy=True, **opts) -> Select: 2102 """ 2103 Set the LIMIT expression. 2104 2105 Example: 2106 >>> select("1").union(select("1")).limit(1).sql() 2107 'SELECT * FROM (SELECT 1 UNION SELECT 1) AS _l_0 LIMIT 1' 2108 2109 Args: 2110 expression (str | int | Expression): the SQL code string to parse. 2111 This can also be an integer. 2112 If a `Limit` instance is passed, this is used as-is. 2113 If another `Expression` instance is passed, it will be wrapped in a `Limit`. 2114 dialect (str): the dialect used to parse the input expression. 2115 copy (bool): if `False`, modify this expression instance in-place. 2116 opts (kwargs): other options to use to parse the input expressions. 2117 2118 Returns: 2119 Select: The limited subqueryable. 2120 """ 2121 return ( 2122 select("*") 2123 .from_(self.subquery(alias="_l_0", copy=copy)) 2124 .limit(expression, dialect=dialect, copy=False, **opts) 2125 ) 2126 2127 def select( 2128 self, 2129 *expressions: ExpOrStr, 2130 append: bool = True, 2131 dialect: DialectType = None, 2132 copy: bool = True, 2133 **opts, 2134 ) -> Union: 2135 """Append to or set the SELECT of the union recursively. 2136 2137 Example: 2138 >>> from sqlglot import parse_one 2139 >>> parse_one("select a from x union select a from y union select a from z").select("b").sql() 2140 'SELECT a, b FROM x UNION SELECT a, b FROM y UNION SELECT a, b FROM z' 2141 2142 Args: 2143 *expressions: the SQL code strings to parse. 2144 If an `Expression` instance is passed, it will be used as-is. 2145 append: if `True`, add to any existing expressions. 2146 Otherwise, this resets the expressions. 2147 dialect: the dialect used to parse the input expressions. 2148 copy: if `False`, modify this expression instance in-place. 2149 opts: other options to use to parse the input expressions. 2150 2151 Returns: 2152 Union: the modified expression. 2153 """ 2154 this = self.copy() if copy else self 2155 this.this.unnest().select(*expressions, append=append, dialect=dialect, copy=False, **opts) 2156 this.expression.unnest().select( 2157 *expressions, append=append, dialect=dialect, copy=False, **opts 2158 ) 2159 return this 2160 2161 @property 2162 def named_selects(self): 2163 return self.this.unnest().named_selects 2164 2165 @property 2166 def is_star(self) -> bool: 2167 return self.this.is_star or self.expression.is_star 2168 2169 @property 2170 def selects(self): 2171 return self.this.unnest().selects 2172 2173 @property 2174 def left(self): 2175 return self.this 2176 2177 @property 2178 def right(self): 2179 return self.expression 2180 2181 2182class Except(Union): 2183 pass 2184 2185 2186class Intersect(Union): 2187 pass 2188 2189 2190class Unnest(UDTF): 2191 arg_types = { 2192 "expressions": True, 2193 "ordinality": False, 2194 "alias": False, 2195 "offset": False, 2196 } 2197 2198 2199class Update(Expression): 2200 arg_types = { 2201 "with": False, 2202 "this": False, 2203 "expressions": True, 2204 "from": False, 2205 "where": False, 2206 "returning": False, 2207 } 2208 2209 2210class Values(UDTF): 2211 arg_types = { 2212 "expressions": True, 2213 "ordinality": False, 2214 "alias": False, 2215 } 2216 2217 2218class Var(Expression): 2219 pass 2220 2221 2222class Schema(Expression): 2223 arg_types = {"this": False, "expressions": False} 2224 2225 2226# Used to represent the FOR UPDATE and FOR SHARE locking read types. 2227# https://dev.mysql.com/doc/refman/8.0/en/innodb-locking-reads.html 2228class Lock(Expression): 2229 arg_types = {"update": True} 2230 2231 2232class Select(Subqueryable): 2233 arg_types = { 2234 "with": False, 2235 "kind": False, 2236 "expressions": False, 2237 "hint": False, 2238 "distinct": False, 2239 "into": False, 2240 "from": False, 2241 **QUERY_MODIFIERS, 2242 } 2243 2244 def from_(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select: 2245 """ 2246 Set the FROM expression. 2247 2248 Example: 2249 >>> Select().from_("tbl").select("x").sql() 2250 'SELECT x FROM tbl' 2251 2252 Args: 2253 *expressions (str | Expression): the SQL code strings to parse. 2254 If a `From` instance is passed, this is used as-is. 2255 If another `Expression` instance is passed, it will be wrapped in a `From`. 2256 append (bool): if `True`, add to any existing expressions. 2257 Otherwise, this flattens all the `From` expression into a single expression. 2258 dialect (str): the dialect used to parse the input expression. 2259 copy (bool): if `False`, modify this expression instance in-place. 2260 opts (kwargs): other options to use to parse the input expressions. 2261 2262 Returns: 2263 Select: the modified expression. 2264 """ 2265 return _apply_child_list_builder( 2266 *expressions, 2267 instance=self, 2268 arg="from", 2269 append=append, 2270 copy=copy, 2271 prefix="FROM", 2272 into=From, 2273 dialect=dialect, 2274 **opts, 2275 ) 2276 2277 def group_by(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select: 2278 """ 2279 Set the GROUP BY expression. 2280 2281 Example: 2282 >>> Select().from_("tbl").select("x", "COUNT(1)").group_by("x").sql() 2283 'SELECT x, COUNT(1) FROM tbl GROUP BY x' 2284 2285 Args: 2286 *expressions (str | Expression): the SQL code strings to parse. 2287 If a `Group` instance is passed, this is used as-is. 2288 If another `Expression` instance is passed, it will be wrapped in a `Group`. 2289 If nothing is passed in then a group by is not applied to the expression 2290 append (bool): if `True`, add to any existing expressions. 2291 Otherwise, this flattens all the `Group` expression into a single expression. 2292 dialect (str): the dialect used to parse the input expression. 2293 copy (bool): if `False`, modify this expression instance in-place. 2294 opts (kwargs): other options to use to parse the input expressions. 2295 2296 Returns: 2297 Select: the modified expression. 2298 """ 2299 if not expressions: 2300 return self if not copy else self.copy() 2301 return _apply_child_list_builder( 2302 *expressions, 2303 instance=self, 2304 arg="group", 2305 append=append, 2306 copy=copy, 2307 prefix="GROUP BY", 2308 into=Group, 2309 dialect=dialect, 2310 **opts, 2311 ) 2312 2313 def order_by(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select: 2314 """ 2315 Set the ORDER BY expression. 2316 2317 Example: 2318 >>> Select().from_("tbl").select("x").order_by("x DESC").sql() 2319 'SELECT x FROM tbl ORDER BY x DESC' 2320 2321 Args: 2322 *expressions (str | Expression): the SQL code strings to parse. 2323 If a `Group` instance is passed, this is used as-is. 2324 If another `Expression` instance is passed, it will be wrapped in a `Order`. 2325 append (bool): if `True`, add to any existing expressions. 2326 Otherwise, this flattens all the `Order` expression into a single expression. 2327 dialect (str): the dialect used to parse the input expression. 2328 copy (bool): if `False`, modify this expression instance in-place. 2329 opts (kwargs): other options to use to parse the input expressions. 2330 2331 Returns: 2332 Select: the modified expression. 2333 """ 2334 return _apply_child_list_builder( 2335 *expressions, 2336 instance=self, 2337 arg="order", 2338 append=append, 2339 copy=copy, 2340 prefix="ORDER BY", 2341 into=Order, 2342 dialect=dialect, 2343 **opts, 2344 ) 2345 2346 def sort_by(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select: 2347 """ 2348 Set the SORT BY expression. 2349 2350 Example: 2351 >>> Select().from_("tbl").select("x").sort_by("x DESC").sql() 2352 'SELECT x FROM tbl SORT BY x DESC' 2353 2354 Args: 2355 *expressions (str | Expression): the SQL code strings to parse. 2356 If a `Group` instance is passed, this is used as-is. 2357 If another `Expression` instance is passed, it will be wrapped in a `SORT`. 2358 append (bool): if `True`, add to any existing expressions. 2359 Otherwise, this flattens all the `Order` expression into a single expression. 2360 dialect (str): the dialect used to parse the input expression. 2361 copy (bool): if `False`, modify this expression instance in-place. 2362 opts (kwargs): other options to use to parse the input expressions. 2363 2364 Returns: 2365 Select: the modified expression. 2366 """ 2367 return _apply_child_list_builder( 2368 *expressions, 2369 instance=self, 2370 arg="sort", 2371 append=append, 2372 copy=copy, 2373 prefix="SORT BY", 2374 into=Sort, 2375 dialect=dialect, 2376 **opts, 2377 ) 2378 2379 def cluster_by(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select: 2380 """ 2381 Set the CLUSTER BY expression. 2382 2383 Example: 2384 >>> Select().from_("tbl").select("x").cluster_by("x DESC").sql() 2385 'SELECT x FROM tbl CLUSTER BY x DESC' 2386 2387 Args: 2388 *expressions (str | Expression): the SQL code strings to parse. 2389 If a `Group` instance is passed, this is used as-is. 2390 If another `Expression` instance is passed, it will be wrapped in a `Cluster`. 2391 append (bool): if `True`, add to any existing expressions. 2392 Otherwise, this flattens all the `Order` expression into a single expression. 2393 dialect (str): the dialect used to parse the input expression. 2394 copy (bool): if `False`, modify this expression instance in-place. 2395 opts (kwargs): other options to use to parse the input expressions. 2396 2397 Returns: 2398 Select: the modified expression. 2399 """ 2400 return _apply_child_list_builder( 2401 *expressions, 2402 instance=self, 2403 arg="cluster", 2404 append=append, 2405 copy=copy, 2406 prefix="CLUSTER BY", 2407 into=Cluster, 2408 dialect=dialect, 2409 **opts, 2410 ) 2411 2412 def limit(self, expression, dialect=None, copy=True, **opts) -> Select: 2413 """ 2414 Set the LIMIT expression. 2415 2416 Example: 2417 >>> Select().from_("tbl").select("x").limit(10).sql() 2418 'SELECT x FROM tbl LIMIT 10' 2419 2420 Args: 2421 expression (str | int | Expression): the SQL code string to parse. 2422 This can also be an integer. 2423 If a `Limit` instance is passed, this is used as-is. 2424 If another `Expression` instance is passed, it will be wrapped in a `Limit`. 2425 dialect (str): the dialect used to parse the input expression. 2426 copy (bool): if `False`, modify this expression instance in-place. 2427 opts (kwargs): other options to use to parse the input expressions. 2428 2429 Returns: 2430 Select: the modified expression. 2431 """ 2432 return _apply_builder( 2433 expression=expression, 2434 instance=self, 2435 arg="limit", 2436 into=Limit, 2437 prefix="LIMIT", 2438 dialect=dialect, 2439 copy=copy, 2440 **opts, 2441 ) 2442 2443 def offset(self, expression, dialect=None, copy=True, **opts) -> Select: 2444 """ 2445 Set the OFFSET expression. 2446 2447 Example: 2448 >>> Select().from_("tbl").select("x").offset(10).sql() 2449 'SELECT x FROM tbl OFFSET 10' 2450 2451 Args: 2452 expression (str | int | Expression): the SQL code string to parse. 2453 This can also be an integer. 2454 If a `Offset` instance is passed, this is used as-is. 2455 If another `Expression` instance is passed, it will be wrapped in a `Offset`. 2456 dialect (str): the dialect used to parse the input expression. 2457 copy (bool): if `False`, modify this expression instance in-place. 2458 opts (kwargs): other options to use to parse the input expressions. 2459 2460 Returns: 2461 Select: the modified expression. 2462 """ 2463 return _apply_builder( 2464 expression=expression, 2465 instance=self, 2466 arg="offset", 2467 into=Offset, 2468 prefix="OFFSET", 2469 dialect=dialect, 2470 copy=copy, 2471 **opts, 2472 ) 2473 2474 def select( 2475 self, 2476 *expressions: ExpOrStr, 2477 append: bool = True, 2478 dialect: DialectType = None, 2479 copy: bool = True, 2480 **opts, 2481 ) -> Select: 2482 """ 2483 Append to or set the SELECT expressions. 2484 2485 Example: 2486 >>> Select().select("x", "y").sql() 2487 'SELECT x, y' 2488 2489 Args: 2490 *expressions: the SQL code strings to parse. 2491 If an `Expression` instance is passed, it will be used as-is. 2492 append: if `True`, add to any existing expressions. 2493 Otherwise, this resets the expressions. 2494 dialect: the dialect used to parse the input expressions. 2495 copy: if `False`, modify this expression instance in-place. 2496 opts: other options to use to parse the input expressions. 2497 2498 Returns: 2499 Select: the modified expression. 2500 """ 2501 return _apply_list_builder( 2502 *expressions, 2503 instance=self, 2504 arg="expressions", 2505 append=append, 2506 dialect=dialect, 2507 copy=copy, 2508 **opts, 2509 ) 2510 2511 def lateral(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select: 2512 """ 2513 Append to or set the LATERAL expressions. 2514 2515 Example: 2516 >>> Select().select("x").lateral("OUTER explode(y) tbl2 AS z").from_("tbl").sql() 2517 'SELECT x FROM tbl LATERAL VIEW OUTER EXPLODE(y) tbl2 AS z' 2518 2519 Args: 2520 *expressions (str | Expression): the SQL code strings to parse. 2521 If an `Expression` instance is passed, it will be used as-is. 2522 append (bool): if `True`, add to any existing expressions. 2523 Otherwise, this resets the expressions. 2524 dialect (str): the dialect used to parse the input expressions. 2525 copy (bool): if `False`, modify this expression instance in-place. 2526 opts (kwargs): other options to use to parse the input expressions. 2527 2528 Returns: 2529 Select: the modified expression. 2530 """ 2531 return _apply_list_builder( 2532 *expressions, 2533 instance=self, 2534 arg="laterals", 2535 append=append, 2536 into=Lateral, 2537 prefix="LATERAL VIEW", 2538 dialect=dialect, 2539 copy=copy, 2540 **opts, 2541 ) 2542 2543 def join( 2544 self, 2545 expression, 2546 on=None, 2547 using=None, 2548 append=True, 2549 join_type=None, 2550 join_alias=None, 2551 dialect=None, 2552 copy=True, 2553 **opts, 2554 ) -> Select: 2555 """ 2556 Append to or set the JOIN expressions. 2557 2558 Example: 2559 >>> Select().select("*").from_("tbl").join("tbl2", on="tbl1.y = tbl2.y").sql() 2560 'SELECT * FROM tbl JOIN tbl2 ON tbl1.y = tbl2.y' 2561 2562 >>> Select().select("1").from_("a").join("b", using=["x", "y", "z"]).sql() 2563 'SELECT 1 FROM a JOIN b USING (x, y, z)' 2564 2565 Use `join_type` to change the type of join: 2566 2567 >>> Select().select("*").from_("tbl").join("tbl2", on="tbl1.y = tbl2.y", join_type="left outer").sql() 2568 'SELECT * FROM tbl LEFT OUTER JOIN tbl2 ON tbl1.y = tbl2.y' 2569 2570 Args: 2571 expression (str | Expression): the SQL code string to parse. 2572 If an `Expression` instance is passed, it will be used as-is. 2573 on (str | Expression): optionally specify the join "on" criteria as a SQL string. 2574 If an `Expression` instance is passed, it will be used as-is. 2575 using (str | Expression): optionally specify the join "using" criteria as a SQL string. 2576 If an `Expression` instance is passed, it will be used as-is. 2577 append (bool): if `True`, add to any existing expressions. 2578 Otherwise, this resets the expressions. 2579 join_type (str): If set, alter the parsed join type 2580 dialect (str): the dialect used to parse the input expressions. 2581 copy (bool): if `False`, modify this expression instance in-place. 2582 opts (kwargs): other options to use to parse the input expressions. 2583 2584 Returns: 2585 Select: the modified expression. 2586 """ 2587 parse_args = {"dialect": dialect, **opts} 2588 2589 try: 2590 expression = maybe_parse(expression, into=Join, prefix="JOIN", **parse_args) 2591 except ParseError: 2592 expression = maybe_parse(expression, into=(Join, Expression), **parse_args) 2593 2594 join = expression if isinstance(expression, Join) else Join(this=expression) 2595 2596 if isinstance(join.this, Select): 2597 join.this.replace(join.this.subquery()) 2598 2599 if join_type: 2600 natural: t.Optional[Token] 2601 side: t.Optional[Token] 2602 kind: t.Optional[Token] 2603 2604 natural, side, kind = maybe_parse(join_type, into="JOIN_TYPE", **parse_args) # type: ignore 2605 2606 if natural: 2607 join.set("natural", True) 2608 if side: 2609 join.set("side", side.text) 2610 if kind: 2611 join.set("kind", kind.text) 2612 2613 if on: 2614 on = and_(*ensure_collection(on), dialect=dialect, **opts) 2615 join.set("on", on) 2616 2617 if using: 2618 join = _apply_list_builder( 2619 *ensure_collection(using), 2620 instance=join, 2621 arg="using", 2622 append=append, 2623 copy=copy, 2624 **opts, 2625 ) 2626 2627 if join_alias: 2628 join.set("this", alias_(join.this, join_alias, table=True)) 2629 return _apply_list_builder( 2630 join, 2631 instance=self, 2632 arg="joins", 2633 append=append, 2634 copy=copy, 2635 **opts, 2636 ) 2637 2638 def where(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select: 2639 """ 2640 Append to or set the WHERE expressions. 2641 2642 Example: 2643 >>> Select().select("x").from_("tbl").where("x = 'a' OR x < 'b'").sql() 2644 "SELECT x FROM tbl WHERE x = 'a' OR x < 'b'" 2645 2646 Args: 2647 *expressions (str | Expression): the SQL code strings to parse. 2648 If an `Expression` instance is passed, it will be used as-is. 2649 Multiple expressions are combined with an AND operator. 2650 append (bool): if `True`, AND the new expressions to any existing expression. 2651 Otherwise, this resets the expression. 2652 dialect (str): the dialect used to parse the input expressions. 2653 copy (bool): if `False`, modify this expression instance in-place. 2654 opts (kwargs): other options to use to parse the input expressions. 2655 2656 Returns: 2657 Select: the modified expression. 2658 """ 2659 return _apply_conjunction_builder( 2660 *expressions, 2661 instance=self, 2662 arg="where", 2663 append=append, 2664 into=Where, 2665 dialect=dialect, 2666 copy=copy, 2667 **opts, 2668 ) 2669 2670 def having(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select: 2671 """ 2672 Append to or set the HAVING expressions. 2673 2674 Example: 2675 >>> Select().select("x", "COUNT(y)").from_("tbl").group_by("x").having("COUNT(y) > 3").sql() 2676 'SELECT x, COUNT(y) FROM tbl GROUP BY x HAVING COUNT(y) > 3' 2677 2678 Args: 2679 *expressions (str | Expression): the SQL code strings to parse. 2680 If an `Expression` instance is passed, it will be used as-is. 2681 Multiple expressions are combined with an AND operator. 2682 append (bool): if `True`, AND the new expressions to any existing expression. 2683 Otherwise, this resets the expression. 2684 dialect (str): the dialect used to parse the input expressions. 2685 copy (bool): if `False`, modify this expression instance in-place. 2686 opts (kwargs): other options to use to parse the input expressions. 2687 2688 Returns: 2689 Select: the modified expression. 2690 """ 2691 return _apply_conjunction_builder( 2692 *expressions, 2693 instance=self, 2694 arg="having", 2695 append=append, 2696 into=Having, 2697 dialect=dialect, 2698 copy=copy, 2699 **opts, 2700 ) 2701 2702 def window(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select: 2703 return _apply_list_builder( 2704 *expressions, 2705 instance=self, 2706 arg="windows", 2707 append=append, 2708 into=Window, 2709 dialect=dialect, 2710 copy=copy, 2711 **opts, 2712 ) 2713 2714 def qualify(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select: 2715 return _apply_conjunction_builder( 2716 *expressions, 2717 instance=self, 2718 arg="qualify", 2719 append=append, 2720 into=Qualify, 2721 dialect=dialect, 2722 copy=copy, 2723 **opts, 2724 ) 2725 2726 def distinct(self, distinct=True, copy=True) -> Select: 2727 """ 2728 Set the OFFSET expression. 2729 2730 Example: 2731 >>> Select().from_("tbl").select("x").distinct().sql() 2732 'SELECT DISTINCT x FROM tbl' 2733 2734 Args: 2735 distinct (bool): whether the Select should be distinct 2736 copy (bool): if `False`, modify this expression instance in-place. 2737 2738 Returns: 2739 Select: the modified expression. 2740 """ 2741 instance = _maybe_copy(self, copy) 2742 instance.set("distinct", Distinct() if distinct else None) 2743 return instance 2744 2745 def ctas(self, table, properties=None, dialect=None, copy=True, **opts) -> Create: 2746 """ 2747 Convert this expression to a CREATE TABLE AS statement. 2748 2749 Example: 2750 >>> Select().select("*").from_("tbl").ctas("x").sql() 2751 'CREATE TABLE x AS SELECT * FROM tbl' 2752 2753 Args: 2754 table (str | Expression): the SQL code string to parse as the table name. 2755 If another `Expression` instance is passed, it will be used as-is. 2756 properties (dict): an optional mapping of table properties 2757 dialect (str): the dialect used to parse the input table. 2758 copy (bool): if `False`, modify this expression instance in-place. 2759 opts (kwargs): other options to use to parse the input table. 2760 2761 Returns: 2762 Create: the CREATE TABLE AS expression 2763 """ 2764 instance = _maybe_copy(self, copy) 2765 table_expression = maybe_parse( 2766 table, 2767 into=Table, 2768 dialect=dialect, 2769 **opts, 2770 ) 2771 properties_expression = None 2772 if properties: 2773 properties_expression = Properties.from_dict(properties) 2774 2775 return Create( 2776 this=table_expression, 2777 kind="table", 2778 expression=instance, 2779 properties=properties_expression, 2780 ) 2781 2782 def lock(self, update: bool = True, copy: bool = True) -> Select: 2783 """ 2784 Set the locking read mode for this expression. 2785 2786 Examples: 2787 >>> Select().select("x").from_("tbl").where("x = 'a'").lock().sql("mysql") 2788 "SELECT x FROM tbl WHERE x = 'a' FOR UPDATE" 2789 2790 >>> Select().select("x").from_("tbl").where("x = 'a'").lock(update=False).sql("mysql") 2791 "SELECT x FROM tbl WHERE x = 'a' FOR SHARE" 2792 2793 Args: 2794 update: if `True`, the locking type will be `FOR UPDATE`, else it will be `FOR SHARE`. 2795 copy: if `False`, modify this expression instance in-place. 2796 2797 Returns: 2798 The modified expression. 2799 """ 2800 2801 inst = _maybe_copy(self, copy) 2802 inst.set("lock", Lock(update=update)) 2803 2804 return inst 2805 2806 @property 2807 def named_selects(self) -> t.List[str]: 2808 return [e.output_name for e in self.expressions if e.alias_or_name] 2809 2810 @property 2811 def is_star(self) -> bool: 2812 return any(expression.is_star for expression in self.expressions) 2813 2814 @property 2815 def selects(self) -> t.List[Expression]: 2816 return self.expressions 2817 2818 2819class Subquery(DerivedTable, Unionable): 2820 arg_types = { 2821 "this": True, 2822 "alias": False, 2823 "with": False, 2824 **QUERY_MODIFIERS, 2825 } 2826 2827 def unnest(self): 2828 """ 2829 Returns the first non subquery. 2830 """ 2831 expression = self 2832 while isinstance(expression, Subquery): 2833 expression = expression.this 2834 return expression 2835 2836 @property 2837 def is_star(self) -> bool: 2838 return self.this.is_star 2839 2840 @property 2841 def output_name(self): 2842 return self.alias 2843 2844 2845class TableSample(Expression): 2846 arg_types = { 2847 "this": False, 2848 "method": False, 2849 "bucket_numerator": False, 2850 "bucket_denominator": False, 2851 "bucket_field": False, 2852 "percent": False, 2853 "rows": False, 2854 "size": False, 2855 "seed": False, 2856 "kind": False, 2857 } 2858 2859 2860class Tag(Expression): 2861 """Tags are used for generating arbitrary sql like SELECT <span>x</span>.""" 2862 2863 arg_types = { 2864 "this": False, 2865 "prefix": False, 2866 "postfix": False, 2867 } 2868 2869 2870class Pivot(Expression): 2871 arg_types = { 2872 "this": False, 2873 "alias": False, 2874 "expressions": True, 2875 "field": True, 2876 "unpivot": True, 2877 "columns": False, 2878 } 2879 2880 2881class Window(Expression): 2882 arg_types = { 2883 "this": True, 2884 "partition_by": False, 2885 "order": False, 2886 "spec": False, 2887 "alias": False, 2888 "over": False, 2889 "first": False, 2890 } 2891 2892 2893class WindowSpec(Expression): 2894 arg_types = { 2895 "kind": False, 2896 "start": False, 2897 "start_side": False, 2898 "end": False, 2899 "end_side": False, 2900 } 2901 2902 2903class Where(Expression): 2904 pass 2905 2906 2907class Star(Expression): 2908 arg_types = {"except": False, "replace": False} 2909 2910 @property 2911 def name(self) -> str: 2912 return "*" 2913 2914 @property 2915 def output_name(self): 2916 return self.name 2917 2918 2919class Parameter(Expression): 2920 arg_types = {"this": True, "wrapped": False} 2921 2922 2923class SessionParameter(Expression): 2924 arg_types = {"this": True, "kind": False} 2925 2926 2927class Placeholder(Expression): 2928 arg_types = {"this": False} 2929 2930 2931class Null(Condition): 2932 arg_types: t.Dict[str, t.Any] = {} 2933 2934 @property 2935 def name(self) -> str: 2936 return "NULL" 2937 2938 2939class Boolean(Condition): 2940 pass 2941 2942 2943class DataType(Expression): 2944 arg_types = { 2945 "this": True, 2946 "expressions": False, 2947 "nested": False, 2948 "values": False, 2949 "prefix": False, 2950 } 2951 2952 class Type(AutoName): 2953 CHAR = auto() 2954 NCHAR = auto() 2955 VARCHAR = auto() 2956 NVARCHAR = auto() 2957 TEXT = auto() 2958 MEDIUMTEXT = auto() 2959 LONGTEXT = auto() 2960 MEDIUMBLOB = auto() 2961 LONGBLOB = auto() 2962 BINARY = auto() 2963 VARBINARY = auto() 2964 INT = auto() 2965 UINT = auto() 2966 TINYINT = auto() 2967 UTINYINT = auto() 2968 SMALLINT = auto() 2969 USMALLINT = auto() 2970 BIGINT = auto() 2971 UBIGINT = auto() 2972 FLOAT = auto() 2973 DOUBLE = auto() 2974 DECIMAL = auto() 2975 BIGDECIMAL = auto() 2976 BIT = auto() 2977 BOOLEAN = auto() 2978 JSON = auto() 2979 JSONB = auto() 2980 INTERVAL = auto() 2981 TIME = auto() 2982 TIMESTAMP = auto() 2983 TIMESTAMPTZ = auto() 2984 TIMESTAMPLTZ = auto() 2985 DATE = auto() 2986 DATETIME = auto() 2987 ARRAY = auto() 2988 MAP = auto() 2989 UUID = auto() 2990 GEOGRAPHY = auto() 2991 GEOMETRY = auto() 2992 STRUCT = auto() 2993 NULLABLE = auto() 2994 HLLSKETCH = auto() 2995 HSTORE = auto() 2996 SUPER = auto() 2997 SERIAL = auto() 2998 SMALLSERIAL = auto() 2999 BIGSERIAL = auto() 3000 XML = auto() 3001 UNIQUEIDENTIFIER = auto() 3002 MONEY = auto() 3003 SMALLMONEY = auto() 3004 ROWVERSION = auto() 3005 IMAGE = auto() 3006 VARIANT = auto() 3007 OBJECT = auto() 3008 INET = auto() 3009 NULL = auto() 3010 UNKNOWN = auto() # Sentinel value, useful for type annotation 3011 3012 TEXT_TYPES = { 3013 Type.CHAR, 3014 Type.NCHAR, 3015 Type.VARCHAR, 3016 Type.NVARCHAR, 3017 Type.TEXT, 3018 } 3019 3020 INTEGER_TYPES = { 3021 Type.INT, 3022 Type.TINYINT, 3023 Type.SMALLINT, 3024 Type.BIGINT, 3025 } 3026 3027 FLOAT_TYPES = { 3028 Type.FLOAT, 3029 Type.DOUBLE, 3030 } 3031 3032 NUMERIC_TYPES = {*INTEGER_TYPES, *FLOAT_TYPES} 3033 3034 TEMPORAL_TYPES = { 3035 Type.TIMESTAMP, 3036 Type.TIMESTAMPTZ, 3037 Type.TIMESTAMPLTZ, 3038 Type.DATE, 3039 Type.DATETIME, 3040 } 3041 3042 @classmethod 3043 def build( 3044 cls, dtype: str | DataType | DataType.Type, dialect: DialectType = None, **kwargs 3045 ) -> DataType: 3046 from sqlglot import parse_one 3047 3048 if isinstance(dtype, str): 3049 if dtype.upper() in cls.Type.__members__: 3050 data_type_exp: t.Optional[Expression] = DataType(this=DataType.Type[dtype.upper()]) 3051 else: 3052 data_type_exp = parse_one(dtype, read=dialect, into=DataType) 3053 if data_type_exp is None: 3054 raise ValueError(f"Unparsable data type value: {dtype}") 3055 elif isinstance(dtype, DataType.Type): 3056 data_type_exp = DataType(this=dtype) 3057 elif isinstance(dtype, DataType): 3058 return dtype 3059 else: 3060 raise ValueError(f"Invalid data type: {type(dtype)}. Expected str or DataType.Type") 3061 return DataType(**{**data_type_exp.args, **kwargs}) 3062 3063 def is_type(self, dtype: DataType.Type) -> bool: 3064 return self.this == dtype 3065 3066 3067# https://www.postgresql.org/docs/15/datatype-pseudo.html 3068class PseudoType(Expression): 3069 pass 3070 3071 3072class StructKwarg(Expression): 3073 arg_types = {"this": True, "expression": True} 3074 3075 3076# WHERE x <OP> EXISTS|ALL|ANY|SOME(SELECT ...) 3077class SubqueryPredicate(Predicate): 3078 pass 3079 3080 3081class All(SubqueryPredicate): 3082 pass 3083 3084 3085class Any(SubqueryPredicate): 3086 pass 3087 3088 3089class Exists(SubqueryPredicate): 3090 pass 3091 3092 3093# Commands to interact with the databases or engines. For most of the command 3094# expressions we parse whatever comes after the command's name as a string. 3095class Command(Expression): 3096 arg_types = {"this": True, "expression": False} 3097 3098 3099class Transaction(Expression): 3100 arg_types = {"this": False, "modes": False} 3101 3102 3103class Commit(Expression): 3104 arg_types = {"chain": False} 3105 3106 3107class Rollback(Expression): 3108 arg_types = {"savepoint": False} 3109 3110 3111class AlterTable(Expression): 3112 arg_types = {"this": True, "actions": True, "exists": False} 3113 3114 3115class AddConstraint(Expression): 3116 arg_types = {"this": False, "expression": False, "enforced": False} 3117 3118 3119class DropPartition(Expression): 3120 arg_types = {"expressions": True, "exists": False} 3121 3122 3123# Binary expressions like (ADD a b) 3124class Binary(Condition): 3125 arg_types = {"this": True, "expression": True} 3126 3127 @property 3128 def left(self): 3129 return self.this 3130 3131 @property 3132 def right(self): 3133 return self.expression 3134 3135 3136class Add(Binary): 3137 pass 3138 3139 3140class Connector(Binary): 3141 pass 3142 3143 3144class And(Connector): 3145 pass 3146 3147 3148class Or(Connector): 3149 pass 3150 3151 3152class BitwiseAnd(Binary): 3153 pass 3154 3155 3156class BitwiseLeftShift(Binary): 3157 pass 3158 3159 3160class BitwiseOr(Binary): 3161 pass 3162 3163 3164class BitwiseRightShift(Binary): 3165 pass 3166 3167 3168class BitwiseXor(Binary): 3169 pass 3170 3171 3172class Div(Binary): 3173 pass 3174 3175 3176class Overlaps(Binary): 3177 pass 3178 3179 3180class Dot(Binary): 3181 @property 3182 def name(self) -> str: 3183 return self.expression.name 3184 3185 @classmethod 3186 def build(self, expressions: t.Sequence[Expression]) -> Dot: 3187 """Build a Dot object with a sequence of expressions.""" 3188 if len(expressions) < 2: 3189 raise ValueError(f"Dot requires >= 2 expressions.") 3190 3191 a, b, *expressions = expressions 3192 dot = Dot(this=a, expression=b) 3193 3194 for expression in expressions: 3195 dot = Dot(this=dot, expression=expression) 3196 3197 return dot 3198 3199 3200class DPipe(Binary): 3201 pass 3202 3203 3204class EQ(Binary, Predicate): 3205 pass 3206 3207 3208class NullSafeEQ(Binary, Predicate): 3209 pass 3210 3211 3212class NullSafeNEQ(Binary, Predicate): 3213 pass 3214 3215 3216class Distance(Binary): 3217 pass 3218 3219 3220class Escape(Binary): 3221 pass 3222 3223 3224class Glob(Binary, Predicate): 3225 pass 3226 3227 3228class GT(Binary, Predicate): 3229 pass 3230 3231 3232class GTE(Binary, Predicate): 3233 pass 3234 3235 3236class ILike(Binary, Predicate): 3237 pass 3238 3239 3240class ILikeAny(Binary, Predicate): 3241 pass 3242 3243 3244class IntDiv(Binary): 3245 pass 3246 3247 3248class Is(Binary, Predicate): 3249 pass 3250 3251 3252class Kwarg(Binary): 3253 """Kwarg in special functions like func(kwarg => y).""" 3254 3255 3256class Like(Binary, Predicate): 3257 pass 3258 3259 3260class LikeAny(Binary, Predicate): 3261 pass 3262 3263 3264class LT(Binary, Predicate): 3265 pass 3266 3267 3268class LTE(Binary, Predicate): 3269 pass 3270 3271 3272class Mod(Binary): 3273 pass 3274 3275 3276class Mul(Binary): 3277 pass 3278 3279 3280class NEQ(Binary, Predicate): 3281 pass 3282 3283 3284class SimilarTo(Binary, Predicate): 3285 pass 3286 3287 3288class Slice(Binary): 3289 arg_types = {"this": False, "expression": False} 3290 3291 3292class Sub(Binary): 3293 pass 3294 3295 3296class ArrayOverlaps(Binary): 3297 pass 3298 3299 3300# Unary Expressions 3301# (NOT a) 3302class Unary(Condition): 3303 pass 3304 3305 3306class BitwiseNot(Unary): 3307 pass 3308 3309 3310class Not(Unary): 3311 pass 3312 3313 3314class Paren(Unary): 3315 arg_types = {"this": True, "with": False} 3316 3317 3318class Neg(Unary): 3319 pass 3320 3321 3322class Alias(Expression): 3323 arg_types = {"this": True, "alias": False} 3324 3325 @property 3326 def output_name(self): 3327 return self.alias 3328 3329 3330class Aliases(Expression): 3331 arg_types = {"this": True, "expressions": True} 3332 3333 @property 3334 def aliases(self): 3335 return self.expressions 3336 3337 3338class AtTimeZone(Expression): 3339 arg_types = {"this": True, "zone": True} 3340 3341 3342class Between(Predicate): 3343 arg_types = {"this": True, "low": True, "high": True} 3344 3345 3346class Bracket(Condition): 3347 arg_types = {"this": True, "expressions": True} 3348 3349 3350class Distinct(Expression): 3351 arg_types = {"expressions": False, "on": False} 3352 3353 3354class In(Predicate): 3355 arg_types = { 3356 "this": True, 3357 "expressions": False, 3358 "query": False, 3359 "unnest": False, 3360 "field": False, 3361 "is_global": False, 3362 } 3363 3364 3365class TimeUnit(Expression): 3366 """Automatically converts unit arg into a var.""" 3367 3368 arg_types = {"unit": False} 3369 3370 def __init__(self, **args): 3371 unit = args.get("unit") 3372 if isinstance(unit, (Column, Literal)): 3373 args["unit"] = Var(this=unit.name) 3374 elif isinstance(unit, Week): 3375 unit.set("this", Var(this=unit.this.name)) 3376 super().__init__(**args) 3377 3378 3379class Interval(TimeUnit): 3380 arg_types = {"this": False, "unit": False} 3381 3382 3383class IgnoreNulls(Expression): 3384 pass 3385 3386 3387class RespectNulls(Expression): 3388 pass 3389 3390 3391# Functions 3392class Func(Condition): 3393 """ 3394 The base class for all function expressions. 3395 3396 Attributes: 3397 is_var_len_args (bool): if set to True the last argument defined in arg_types will be 3398 treated as a variable length argument and the argument's value will be stored as a list. 3399 _sql_names (list): determines the SQL name (1st item in the list) and aliases (subsequent items) 3400 for this function expression. These values are used to map this node to a name during parsing 3401 as well as to provide the function's name during SQL string generation. By default the SQL 3402 name is set to the expression's class name transformed to snake case. 3403 """ 3404 3405 is_var_len_args = False 3406 3407 @classmethod 3408 def from_arg_list(cls, args): 3409 if cls.is_var_len_args: 3410 all_arg_keys = list(cls.arg_types) 3411 # If this function supports variable length argument treat the last argument as such. 3412 non_var_len_arg_keys = all_arg_keys[:-1] if cls.is_var_len_args else all_arg_keys 3413 num_non_var = len(non_var_len_arg_keys) 3414 3415 args_dict = {arg_key: arg for arg, arg_key in zip(args, non_var_len_arg_keys)} 3416 args_dict[all_arg_keys[-1]] = args[num_non_var:] 3417 else: 3418 args_dict = {arg_key: arg for arg, arg_key in zip(args, cls.arg_types)} 3419 3420 return cls(**args_dict) 3421 3422 @classmethod 3423 def sql_names(cls): 3424 if cls is Func: 3425 raise NotImplementedError( 3426 "SQL name is only supported by concrete function implementations" 3427 ) 3428 if "_sql_names" not in cls.__dict__: 3429 cls._sql_names = [camel_to_snake_case(cls.__name__)] 3430 return cls._sql_names 3431 3432 @classmethod 3433 def sql_name(cls): 3434 return cls.sql_names()[0] 3435 3436 @classmethod 3437 def default_parser_mappings(cls): 3438 return {name: cls.from_arg_list for name in cls.sql_names()} 3439 3440 3441class AggFunc(Func): 3442 pass 3443 3444 3445class Abs(Func): 3446 pass 3447 3448 3449class Anonymous(Func): 3450 arg_types = {"this": True, "expressions": False} 3451 is_var_len_args = True 3452 3453 3454# https://docs.snowflake.com/en/sql-reference/functions/hll 3455# https://docs.aws.amazon.com/redshift/latest/dg/r_HLL_function.html 3456class Hll(AggFunc): 3457 arg_types = {"this": True, "expressions": False} 3458 is_var_len_args = True 3459 3460 3461class ApproxDistinct(AggFunc): 3462 arg_types = {"this": True, "accuracy": False} 3463 3464 3465class Array(Func): 3466 arg_types = {"expressions": False} 3467 is_var_len_args = True 3468 3469 3470# https://docs.snowflake.com/en/sql-reference/functions/to_char 3471class ToChar(Func): 3472 arg_types = {"this": True, "format": False} 3473 3474 3475class GenerateSeries(Func): 3476 arg_types = {"start": True, "end": True, "step": False} 3477 3478 3479class ArrayAgg(AggFunc): 3480 pass 3481 3482 3483class ArrayAll(Func): 3484 arg_types = {"this": True, "expression": True} 3485 3486 3487class ArrayAny(Func): 3488 arg_types = {"this": True, "expression": True} 3489 3490 3491class ArrayConcat(Func): 3492 arg_types = {"this": True, "expressions": False} 3493 is_var_len_args = True 3494 3495 3496class ArrayContains(Binary, Func): 3497 pass 3498 3499 3500class ArrayContained(Binary): 3501 pass 3502 3503 3504class ArrayFilter(Func): 3505 arg_types = {"this": True, "expression": True} 3506 _sql_names = ["FILTER", "ARRAY_FILTER"] 3507 3508 3509class ArrayJoin(Func): 3510 arg_types = {"this": True, "expression": True, "null": False} 3511 3512 3513class ArraySize(Func): 3514 arg_types = {"this": True, "expression": False} 3515 3516 3517class ArraySort(Func): 3518 arg_types = {"this": True, "expression": False} 3519 3520 3521class ArraySum(Func): 3522 pass 3523 3524 3525class ArrayUnionAgg(AggFunc): 3526 pass 3527 3528 3529class Avg(AggFunc): 3530 pass 3531 3532 3533class AnyValue(AggFunc): 3534 pass 3535 3536 3537class Case(Func): 3538 arg_types = {"this": False, "ifs": True, "default": False} 3539 3540 def when(self, condition: ExpOrStr, then: ExpOrStr, copy: bool = True, **opts) -> Case: 3541 this = self.copy() if copy else self 3542 this.append("ifs", If(this=maybe_parse(condition, **opts), true=maybe_parse(then, **opts))) 3543 return this 3544 3545 def else_(self, condition: ExpOrStr, copy: bool = True, **opts) -> Case: 3546 this = self.copy() if copy else self 3547 this.set("default", maybe_parse(condition, **opts)) 3548 return this 3549 3550 3551class Cast(Func): 3552 arg_types = {"this": True, "to": True} 3553 3554 @property 3555 def name(self) -> str: 3556 return self.this.name 3557 3558 @property 3559 def to(self): 3560 return self.args["to"] 3561 3562 @property 3563 def output_name(self): 3564 return self.name 3565 3566 def is_type(self, dtype: DataType.Type) -> bool: 3567 return self.to.is_type(dtype) 3568 3569 3570class Collate(Binary): 3571 pass 3572 3573 3574class TryCast(Cast): 3575 pass 3576 3577 3578class Ceil(Func): 3579 arg_types = {"this": True, "decimals": False} 3580 _sql_names = ["CEIL", "CEILING"] 3581 3582 3583class Coalesce(Func): 3584 arg_types = {"this": True, "expressions": False} 3585 is_var_len_args = True 3586 3587 3588class Concat(Func): 3589 arg_types = {"expressions": True} 3590 is_var_len_args = True 3591 3592 3593class ConcatWs(Concat): 3594 _sql_names = ["CONCAT_WS"] 3595 3596 3597class Count(AggFunc): 3598 arg_types = {"this": False} 3599 3600 3601class CountIf(AggFunc): 3602 pass 3603 3604 3605class CurrentDate(Func): 3606 arg_types = {"this": False} 3607 3608 3609class CurrentDatetime(Func): 3610 arg_types = {"this": False} 3611 3612 3613class CurrentTime(Func): 3614 arg_types = {"this": False} 3615 3616 3617class CurrentTimestamp(Func): 3618 arg_types = {"this": False} 3619 3620 3621class CurrentUser(Func): 3622 arg_types = {"this": False} 3623 3624 3625class DateAdd(Func, TimeUnit): 3626 arg_types = {"this": True, "expression": True, "unit": False} 3627 3628 3629class DateSub(Func, TimeUnit): 3630 arg_types = {"this": True, "expression": True, "unit": False} 3631 3632 3633class DateDiff(Func, TimeUnit): 3634 _sql_names = ["DATEDIFF", "DATE_DIFF"] 3635 arg_types = {"this": True, "expression": True, "unit": False} 3636 3637 3638class DateTrunc(Func): 3639 arg_types = {"unit": True, "this": True, "zone": False} 3640 3641 3642class DatetimeAdd(Func, TimeUnit): 3643 arg_types = {"this": True, "expression": True, "unit": False} 3644 3645 3646class DatetimeSub(Func, TimeUnit): 3647 arg_types = {"this": True, "expression": True, "unit": False} 3648 3649 3650class DatetimeDiff(Func, TimeUnit): 3651 arg_types = {"this": True, "expression": True, "unit": False} 3652 3653 3654class DatetimeTrunc(Func, TimeUnit): 3655 arg_types = {"this": True, "unit": True, "zone": False} 3656 3657 3658class DayOfWeek(Func): 3659 _sql_names = ["DAY_OF_WEEK", "DAYOFWEEK"] 3660 3661 3662class DayOfMonth(Func): 3663 _sql_names = ["DAY_OF_MONTH", "DAYOFMONTH"] 3664 3665 3666class DayOfYear(Func): 3667 _sql_names = ["DAY_OF_YEAR", "DAYOFYEAR"] 3668 3669 3670class WeekOfYear(Func): 3671 _sql_names = ["WEEK_OF_YEAR", "WEEKOFYEAR"] 3672 3673 3674class LastDateOfMonth(Func): 3675 pass 3676 3677 3678class Extract(Func): 3679 arg_types = {"this": True, "expression": True} 3680 3681 3682class TimestampAdd(Func, TimeUnit): 3683 arg_types = {"this": True, "expression": True, "unit": False} 3684 3685 3686class TimestampSub(Func, TimeUnit): 3687 arg_types = {"this": True, "expression": True, "unit": False} 3688 3689 3690class TimestampDiff(Func, TimeUnit): 3691 arg_types = {"this": True, "expression": True, "unit": False} 3692 3693 3694class TimestampTrunc(Func, TimeUnit): 3695 arg_types = {"this": True, "unit": True, "zone": False} 3696 3697 3698class TimeAdd(Func, TimeUnit): 3699 arg_types = {"this": True, "expression": True, "unit": False} 3700 3701 3702class TimeSub(Func, TimeUnit): 3703 arg_types = {"this": True, "expression": True, "unit": False} 3704 3705 3706class TimeDiff(Func, TimeUnit): 3707 arg_types = {"this": True, "expression": True, "unit": False} 3708 3709 3710class TimeTrunc(Func, TimeUnit): 3711 arg_types = {"this": True, "unit": True, "zone": False} 3712 3713 3714class DateFromParts(Func): 3715 _sql_names = ["DATEFROMPARTS"] 3716 arg_types = {"year": True, "month": True, "day": True} 3717 3718 3719class DateStrToDate(Func): 3720 pass 3721 3722 3723class DateToDateStr(Func): 3724 pass 3725 3726 3727class DateToDi(Func): 3728 pass 3729 3730 3731class Day(Func): 3732 pass 3733 3734 3735class Decode(Func): 3736 arg_types = {"this": True, "charset": True, "replace": False} 3737 3738 3739class DiToDate(Func): 3740 pass 3741 3742 3743class Encode(Func): 3744 arg_types = {"this": True, "charset": True} 3745 3746 3747class Exp(Func): 3748 pass 3749 3750 3751class Explode(Func): 3752 pass 3753 3754 3755class ExponentialTimeDecayedAvg(AggFunc): 3756 arg_types = {"this": True, "time": False, "decay": False} 3757 3758 3759class Floor(Func): 3760 arg_types = {"this": True, "decimals": False} 3761 3762 3763class Greatest(Func): 3764 arg_types = {"this": True, "expressions": False} 3765 is_var_len_args = True 3766 3767 3768class GroupConcat(Func): 3769 arg_types = {"this": True, "separator": False} 3770 3771 3772class GroupUniqArray(AggFunc): 3773 arg_types = {"this": True, "size": False} 3774 3775 3776class Hex(Func): 3777 pass 3778 3779 3780class Histogram(AggFunc): 3781 arg_types = {"this": True, "bins": False} 3782 3783 3784class If(Func): 3785 arg_types = {"this": True, "true": True, "false": False} 3786 3787 3788class IfNull(Func): 3789 arg_types = {"this": True, "expression": False} 3790 _sql_names = ["IFNULL", "NVL"] 3791 3792 3793class Initcap(Func): 3794 pass 3795 3796 3797class JSONKeyValue(Expression): 3798 arg_types = {"this": True, "expression": True} 3799 3800 3801class JSONObject(Func): 3802 arg_types = { 3803 "expressions": False, 3804 "null_handling": False, 3805 "unique_keys": False, 3806 "return_type": False, 3807 "format_json": False, 3808 "encoding": False, 3809 } 3810 3811 3812class JSONBContains(Binary): 3813 _sql_names = ["JSONB_CONTAINS"] 3814 3815 3816class JSONExtract(Binary, Func): 3817 _sql_names = ["JSON_EXTRACT"] 3818 3819 3820class JSONExtractScalar(JSONExtract): 3821 _sql_names = ["JSON_EXTRACT_SCALAR"] 3822 3823 3824class JSONBExtract(JSONExtract): 3825 _sql_names = ["JSONB_EXTRACT"] 3826 3827 3828class JSONBExtractScalar(JSONExtract): 3829 _sql_names = ["JSONB_EXTRACT_SCALAR"] 3830 3831 3832class JSONFormat(Func): 3833 arg_types = {"this": False, "options": False} 3834 _sql_names = ["JSON_FORMAT"] 3835 3836 3837class Least(Func): 3838 arg_types = {"expressions": False} 3839 is_var_len_args = True 3840 3841 3842class Length(Func): 3843 pass 3844 3845 3846class Levenshtein(Func): 3847 arg_types = { 3848 "this": True, 3849 "expression": False, 3850 "ins_cost": False, 3851 "del_cost": False, 3852 "sub_cost": False, 3853 } 3854 3855 3856class Ln(Func): 3857 pass 3858 3859 3860class Log(Func): 3861 arg_types = {"this": True, "expression": False} 3862 3863 3864class Log2(Func): 3865 pass 3866 3867 3868class Log10(Func): 3869 pass 3870 3871 3872class LogicalOr(AggFunc): 3873 _sql_names = ["LOGICAL_OR", "BOOL_OR", "BOOLOR_AGG"] 3874 3875 3876class LogicalAnd(AggFunc): 3877 _sql_names = ["LOGICAL_AND", "BOOL_AND", "BOOLAND_AGG"] 3878 3879 3880class Lower(Func): 3881 _sql_names = ["LOWER", "LCASE"] 3882 3883 3884class Map(Func): 3885 arg_types = {"keys": False, "values": False} 3886 3887 3888class StarMap(Func): 3889 pass 3890 3891 3892class VarMap(Func): 3893 arg_types = {"keys": True, "values": True} 3894 is_var_len_args = True 3895 3896 3897# https://dev.mysql.com/doc/refman/8.0/en/fulltext-search.html 3898class MatchAgainst(Func): 3899 arg_types = {"this": True, "expressions": True, "modifier": False} 3900 3901 3902class Max(AggFunc): 3903 arg_types = {"this": True, "expressions": False} 3904 is_var_len_args = True 3905 3906 3907class MD5(Func): 3908 _sql_names = ["MD5"] 3909 3910 3911class Min(AggFunc): 3912 arg_types = {"this": True, "expressions": False} 3913 is_var_len_args = True 3914 3915 3916class Month(Func): 3917 pass 3918 3919 3920class Nvl2(Func): 3921 arg_types = {"this": True, "true": True, "false": False} 3922 3923 3924class Posexplode(Func): 3925 pass 3926 3927 3928class Pow(Binary, Func): 3929 _sql_names = ["POWER", "POW"] 3930 3931 3932class PercentileCont(AggFunc): 3933 pass 3934 3935 3936class PercentileDisc(AggFunc): 3937 pass 3938 3939 3940class Quantile(AggFunc): 3941 arg_types = {"this": True, "quantile": True} 3942 3943 3944# Clickhouse-specific: 3945# https://clickhouse.com/docs/en/sql-reference/aggregate-functions/reference/quantiles/#quantiles 3946class Quantiles(AggFunc): 3947 arg_types = {"parameters": True, "expressions": True} 3948 is_var_len_args = True 3949 3950 3951class QuantileIf(AggFunc): 3952 arg_types = {"parameters": True, "expressions": True} 3953 3954 3955class ApproxQuantile(Quantile): 3956 arg_types = {"this": True, "quantile": True, "accuracy": False, "weight": False} 3957 3958 3959class RangeN(Func): 3960 arg_types = {"this": True, "expressions": True, "each": False} 3961 3962 3963class ReadCSV(Func): 3964 _sql_names = ["READ_CSV"] 3965 is_var_len_args = True 3966 arg_types = {"this": True, "expressions": False} 3967 3968 3969class Reduce(Func): 3970 arg_types = {"this": True, "initial": True, "merge": True, "finish": False} 3971 3972 3973class RegexpExtract(Func): 3974 arg_types = { 3975 "this": True, 3976 "expression": True, 3977 "position": False, 3978 "occurrence": False, 3979 "group": False, 3980 } 3981 3982 3983class RegexpLike(Func): 3984 arg_types = {"this": True, "expression": True, "flag": False} 3985 3986 3987class RegexpILike(Func): 3988 arg_types = {"this": True, "expression": True, "flag": False} 3989 3990 3991# https://spark.apache.org/docs/latest/api/python/reference/pyspark.sql/api/pyspark.sql.functions.split.html 3992# limit is the number of times a pattern is applied 3993class RegexpSplit(Func): 3994 arg_types = {"this": True, "expression": True, "limit": False} 3995 3996 3997class Repeat(Func): 3998 arg_types = {"this": True, "times": True} 3999 4000 4001class Round(Func): 4002 arg_types = {"this": True, "decimals": False} 4003 4004 4005class RowNumber(Func): 4006 arg_types: t.Dict[str, t.Any] = {} 4007 4008 4009class SafeDivide(Func): 4010 arg_types = {"this": True, "expression": True} 4011 4012 4013class SetAgg(AggFunc): 4014 pass 4015 4016 4017class SHA(Func): 4018 _sql_names = ["SHA", "SHA1"] 4019 4020 4021class SHA2(Func): 4022 _sql_names = ["SHA2"] 4023 arg_types = {"this": True, "length": False} 4024 4025 4026class SortArray(Func): 4027 arg_types = {"this": True, "asc": False} 4028 4029 4030class Split(Func): 4031 arg_types = {"this": True, "expression": True, "limit": False} 4032 4033 4034# Start may be omitted in the case of postgres 4035# https://www.postgresql.org/docs/9.1/functions-string.html @ Table 9-6 4036class Substring(Func): 4037 arg_types = {"this": True, "start": False, "length": False} 4038 4039 4040class StrPosition(Func): 4041 arg_types = { 4042 "this": True, 4043 "substr": True, 4044 "position": False, 4045 "instance": False, 4046 } 4047 4048 4049class StrToDate(Func): 4050 arg_types = {"this": True, "format": True} 4051 4052 4053class StrToTime(Func): 4054 arg_types = {"this": True, "format": True} 4055 4056 4057# Spark allows unix_timestamp() 4058# https://spark.apache.org/docs/3.1.3/api/python/reference/api/pyspark.sql.functions.unix_timestamp.html 4059class StrToUnix(Func): 4060 arg_types = {"this": False, "format": False} 4061 4062 4063class NumberToStr(Func): 4064 arg_types = {"this": True, "format": True} 4065 4066 4067class Struct(Func): 4068 arg_types = {"expressions": True} 4069 is_var_len_args = True 4070 4071 4072class StructExtract(Func): 4073 arg_types = {"this": True, "expression": True} 4074 4075 4076class Sum(AggFunc): 4077 pass 4078 4079 4080class Sqrt(Func): 4081 pass 4082 4083 4084class Stddev(AggFunc): 4085 pass 4086 4087 4088class StddevPop(AggFunc): 4089 pass 4090 4091 4092class StddevSamp(AggFunc): 4093 pass 4094 4095 4096class TimeToStr(Func): 4097 arg_types = {"this": True, "format": True} 4098 4099 4100class TimeToTimeStr(Func): 4101 pass 4102 4103 4104class TimeToUnix(Func): 4105 pass 4106 4107 4108class TimeStrToDate(Func): 4109 pass 4110 4111 4112class TimeStrToTime(Func): 4113 pass 4114 4115 4116class TimeStrToUnix(Func): 4117 pass 4118 4119 4120class Trim(Func): 4121 arg_types = { 4122 "this": True, 4123 "expression": False, 4124 "position": False, 4125 "collation": False, 4126 } 4127 4128 4129class TsOrDsAdd(Func, TimeUnit): 4130 arg_types = {"this": True, "expression": True, "unit": False} 4131 4132 4133class TsOrDsToDateStr(Func): 4134 pass 4135 4136 4137class TsOrDsToDate(Func): 4138 arg_types = {"this": True, "format": False} 4139 4140 4141class TsOrDiToDi(Func): 4142 pass 4143 4144 4145class Unhex(Func): 4146 pass 4147 4148 4149class UnixToStr(Func): 4150 arg_types = {"this": True, "format": False} 4151 4152 4153# https://prestodb.io/docs/current/functions/datetime.html 4154# presto has weird zone/hours/minutes 4155class UnixToTime(Func): 4156 arg_types = {"this": True, "scale": False, "zone": False, "hours": False, "minutes": False} 4157 4158 SECONDS = Literal.string("seconds") 4159 MILLIS = Literal.string("millis") 4160 MICROS = Literal.string("micros") 4161 4162 4163class UnixToTimeStr(Func): 4164 pass 4165 4166 4167class Upper(Func): 4168 _sql_names = ["UPPER", "UCASE"] 4169 4170 4171class Variance(AggFunc): 4172 _sql_names = ["VARIANCE", "VARIANCE_SAMP", "VAR_SAMP"] 4173 4174 4175class VariancePop(AggFunc): 4176 _sql_names = ["VARIANCE_POP", "VAR_POP"] 4177 4178 4179class Week(Func): 4180 arg_types = {"this": True, "mode": False} 4181 4182 4183class XMLTable(Func): 4184 arg_types = {"this": True, "passing": False, "columns": False, "by_ref": False} 4185 4186 4187class Year(Func): 4188 pass 4189 4190 4191class Use(Expression): 4192 arg_types = {"this": True, "kind": False} 4193 4194 4195class Merge(Expression): 4196 arg_types = {"this": True, "using": True, "on": True, "expressions": True} 4197 4198 4199class When(Func): 4200 arg_types = {"matched": True, "source": False, "condition": False, "then": True} 4201 4202 4203# https://docs.oracle.com/javadb/10.8.3.0/ref/rrefsqljnextvaluefor.html 4204# https://learn.microsoft.com/en-us/sql/t-sql/functions/next-value-for-transact-sql?view=sql-server-ver16 4205class NextValueFor(Func): 4206 arg_types = {"this": True, "order": False} 4207 4208 4209def _norm_arg(arg): 4210 return arg.lower() if type(arg) is str else arg 4211 4212 4213ALL_FUNCTIONS = subclasses(__name__, Func, (AggFunc, Anonymous, Func)) 4214 4215 4216# Helpers 4217@t.overload 4218def maybe_parse( 4219 sql_or_expression: ExpOrStr, 4220 *, 4221 into: t.Type[E], 4222 dialect: DialectType = None, 4223 prefix: t.Optional[str] = None, 4224 copy: bool = False, 4225 **opts, 4226) -> E: 4227 ... 4228 4229 4230@t.overload 4231def maybe_parse( 4232 sql_or_expression: str | E, 4233 *, 4234 into: t.Optional[IntoType] = None, 4235 dialect: DialectType = None, 4236 prefix: t.Optional[str] = None, 4237 copy: bool = False, 4238 **opts, 4239) -> E: 4240 ... 4241 4242 4243def maybe_parse( 4244 sql_or_expression: ExpOrStr, 4245 *, 4246 into: t.Optional[IntoType] = None, 4247 dialect: DialectType = None, 4248 prefix: t.Optional[str] = None, 4249 copy: bool = False, 4250 **opts, 4251) -> Expression: 4252 """Gracefully handle a possible string or expression. 4253 4254 Example: 4255 >>> maybe_parse("1") 4256 (LITERAL this: 1, is_string: False) 4257 >>> maybe_parse(to_identifier("x")) 4258 (IDENTIFIER this: x, quoted: False) 4259 4260 Args: 4261 sql_or_expression: the SQL code string or an expression 4262 into: the SQLGlot Expression to parse into 4263 dialect: the dialect used to parse the input expressions (in the case that an 4264 input expression is a SQL string). 4265 prefix: a string to prefix the sql with before it gets parsed 4266 (automatically includes a space) 4267 copy: whether or not to copy the expression. 4268 **opts: other options to use to parse the input expressions (again, in the case 4269 that an input expression is a SQL string). 4270 4271 Returns: 4272 Expression: the parsed or given expression. 4273 """ 4274 if isinstance(sql_or_expression, Expression): 4275 if copy: 4276 return sql_or_expression.copy() 4277 return sql_or_expression 4278 4279 import sqlglot 4280 4281 sql = str(sql_or_expression) 4282 if prefix: 4283 sql = f"{prefix} {sql}" 4284 return sqlglot.parse_one(sql, read=dialect, into=into, **opts) 4285 4286 4287def _maybe_copy(instance, copy=True): 4288 return instance.copy() if copy else instance 4289 4290 4291def _is_wrong_expression(expression, into): 4292 return isinstance(expression, Expression) and not isinstance(expression, into) 4293 4294 4295def _apply_builder( 4296 expression, 4297 instance, 4298 arg, 4299 copy=True, 4300 prefix=None, 4301 into=None, 4302 dialect=None, 4303 **opts, 4304): 4305 if _is_wrong_expression(expression, into): 4306 expression = into(this=expression) 4307 instance = _maybe_copy(instance, copy) 4308 expression = maybe_parse( 4309 sql_or_expression=expression, 4310 prefix=prefix, 4311 into=into, 4312 dialect=dialect, 4313 **opts, 4314 ) 4315 instance.set(arg, expression) 4316 return instance 4317 4318 4319def _apply_child_list_builder( 4320 *expressions, 4321 instance, 4322 arg, 4323 append=True, 4324 copy=True, 4325 prefix=None, 4326 into=None, 4327 dialect=None, 4328 properties=None, 4329 **opts, 4330): 4331 instance = _maybe_copy(instance, copy) 4332 parsed = [] 4333 for expression in expressions: 4334 if _is_wrong_expression(expression, into): 4335 expression = into(expressions=[expression]) 4336 expression = maybe_parse( 4337 expression, 4338 into=into, 4339 dialect=dialect, 4340 prefix=prefix, 4341 **opts, 4342 ) 4343 parsed.extend(expression.expressions) 4344 4345 existing = instance.args.get(arg) 4346 if append and existing: 4347 parsed = existing.expressions + parsed 4348 4349 child = into(expressions=parsed) 4350 for k, v in (properties or {}).items(): 4351 child.set(k, v) 4352 instance.set(arg, child) 4353 return instance 4354 4355 4356def _apply_list_builder( 4357 *expressions, 4358 instance, 4359 arg, 4360 append=True, 4361 copy=True, 4362 prefix=None, 4363 into=None, 4364 dialect=None, 4365 **opts, 4366): 4367 inst = _maybe_copy(instance, copy) 4368 4369 expressions = [ 4370 maybe_parse( 4371 sql_or_expression=expression, 4372 into=into, 4373 prefix=prefix, 4374 dialect=dialect, 4375 **opts, 4376 ) 4377 for expression in expressions 4378 ] 4379 4380 existing_expressions = inst.args.get(arg) 4381 if append and existing_expressions: 4382 expressions = existing_expressions + expressions 4383 4384 inst.set(arg, expressions) 4385 return inst 4386 4387 4388def _apply_conjunction_builder( 4389 *expressions, 4390 instance, 4391 arg, 4392 into=None, 4393 append=True, 4394 copy=True, 4395 dialect=None, 4396 **opts, 4397): 4398 expressions = [exp for exp in expressions if exp is not None and exp != ""] 4399 if not expressions: 4400 return instance 4401 4402 inst = _maybe_copy(instance, copy) 4403 4404 existing = inst.args.get(arg) 4405 if append and existing is not None: 4406 expressions = [existing.this if into else existing] + list(expressions) 4407 4408 node = and_(*expressions, dialect=dialect, **opts) 4409 4410 inst.set(arg, into(this=node) if into else node) 4411 return inst 4412 4413 4414def _combine(expressions, operator, dialect=None, **opts): 4415 expressions = [condition(expression, dialect=dialect, **opts) for expression in expressions] 4416 this = expressions[0] 4417 if expressions[1:]: 4418 this = _wrap(this, Connector) 4419 for expression in expressions[1:]: 4420 this = operator(this=this, expression=_wrap(expression, Connector)) 4421 return this 4422 4423 4424def _wrap(expression: E, kind: t.Type[Expression]) -> E | Paren: 4425 if isinstance(expression, kind): 4426 return Paren(this=expression) 4427 return expression 4428 4429 4430def union(left, right, distinct=True, dialect=None, **opts): 4431 """ 4432 Initializes a syntax tree from one UNION expression. 4433 4434 Example: 4435 >>> union("SELECT * FROM foo", "SELECT * FROM bla").sql() 4436 'SELECT * FROM foo UNION SELECT * FROM bla' 4437 4438 Args: 4439 left (str | Expression): the SQL code string corresponding to the left-hand side. 4440 If an `Expression` instance is passed, it will be used as-is. 4441 right (str | Expression): the SQL code string corresponding to the right-hand side. 4442 If an `Expression` instance is passed, it will be used as-is. 4443 distinct (bool): set the DISTINCT flag if and only if this is true. 4444 dialect (str): the dialect used to parse the input expression. 4445 opts (kwargs): other options to use to parse the input expressions. 4446 Returns: 4447 Union: the syntax tree for the UNION expression. 4448 """ 4449 left = maybe_parse(sql_or_expression=left, dialect=dialect, **opts) 4450 right = maybe_parse(sql_or_expression=right, dialect=dialect, **opts) 4451 4452 return Union(this=left, expression=right, distinct=distinct) 4453 4454 4455def intersect(left, right, distinct=True, dialect=None, **opts): 4456 """ 4457 Initializes a syntax tree from one INTERSECT expression. 4458 4459 Example: 4460 >>> intersect("SELECT * FROM foo", "SELECT * FROM bla").sql() 4461 'SELECT * FROM foo INTERSECT SELECT * FROM bla' 4462 4463 Args: 4464 left (str | Expression): the SQL code string corresponding to the left-hand side. 4465 If an `Expression` instance is passed, it will be used as-is. 4466 right (str | Expression): the SQL code string corresponding to the right-hand side. 4467 If an `Expression` instance is passed, it will be used as-is. 4468 distinct (bool): set the DISTINCT flag if and only if this is true. 4469 dialect (str): the dialect used to parse the input expression. 4470 opts (kwargs): other options to use to parse the input expressions. 4471 Returns: 4472 Intersect: the syntax tree for the INTERSECT expression. 4473 """ 4474 left = maybe_parse(sql_or_expression=left, dialect=dialect, **opts) 4475 right = maybe_parse(sql_or_expression=right, dialect=dialect, **opts) 4476 4477 return Intersect(this=left, expression=right, distinct=distinct) 4478 4479 4480def except_(left, right, distinct=True, dialect=None, **opts): 4481 """ 4482 Initializes a syntax tree from one EXCEPT expression. 4483 4484 Example: 4485 >>> except_("SELECT * FROM foo", "SELECT * FROM bla").sql() 4486 'SELECT * FROM foo EXCEPT SELECT * FROM bla' 4487 4488 Args: 4489 left (str | Expression): the SQL code string corresponding to the left-hand side. 4490 If an `Expression` instance is passed, it will be used as-is. 4491 right (str | Expression): the SQL code string corresponding to the right-hand side. 4492 If an `Expression` instance is passed, it will be used as-is. 4493 distinct (bool): set the DISTINCT flag if and only if this is true. 4494 dialect (str): the dialect used to parse the input expression. 4495 opts (kwargs): other options to use to parse the input expressions. 4496 Returns: 4497 Except: the syntax tree for the EXCEPT statement. 4498 """ 4499 left = maybe_parse(sql_or_expression=left, dialect=dialect, **opts) 4500 right = maybe_parse(sql_or_expression=right, dialect=dialect, **opts) 4501 4502 return Except(this=left, expression=right, distinct=distinct) 4503 4504 4505def select(*expressions: ExpOrStr, dialect: DialectType = None, **opts) -> Select: 4506 """ 4507 Initializes a syntax tree from one or multiple SELECT expressions. 4508 4509 Example: 4510 >>> select("col1", "col2").from_("tbl").sql() 4511 'SELECT col1, col2 FROM tbl' 4512 4513 Args: 4514 *expressions: the SQL code string to parse as the expressions of a 4515 SELECT statement. If an Expression instance is passed, this is used as-is. 4516 dialect: the dialect used to parse the input expressions (in the case that an 4517 input expression is a SQL string). 4518 **opts: other options to use to parse the input expressions (again, in the case 4519 that an input expression is a SQL string). 4520 4521 Returns: 4522 Select: the syntax tree for the SELECT statement. 4523 """ 4524 return Select().select(*expressions, dialect=dialect, **opts) 4525 4526 4527def from_(*expressions, dialect=None, **opts) -> Select: 4528 """ 4529 Initializes a syntax tree from a FROM expression. 4530 4531 Example: 4532 >>> from_("tbl").select("col1", "col2").sql() 4533 'SELECT col1, col2 FROM tbl' 4534 4535 Args: 4536 *expressions (str | Expression): the SQL code string to parse as the FROM expressions of a 4537 SELECT statement. If an Expression instance is passed, this is used as-is. 4538 dialect (str): the dialect used to parse the input expression (in the case that the 4539 input expression is a SQL string). 4540 **opts: other options to use to parse the input expressions (again, in the case 4541 that the input expression is a SQL string). 4542 4543 Returns: 4544 Select: the syntax tree for the SELECT statement. 4545 """ 4546 return Select().from_(*expressions, dialect=dialect, **opts) 4547 4548 4549def update( 4550 table: str | Table, 4551 properties: dict, 4552 where: t.Optional[ExpOrStr] = None, 4553 from_: t.Optional[ExpOrStr] = None, 4554 dialect: DialectType = None, 4555 **opts, 4556) -> Update: 4557 """ 4558 Creates an update statement. 4559 4560 Example: 4561 >>> update("my_table", {"x": 1, "y": "2", "z": None}, from_="baz", where="id > 1").sql() 4562 "UPDATE my_table SET x = 1, y = '2', z = NULL FROM baz WHERE id > 1" 4563 4564 Args: 4565 *properties: dictionary of properties to set which are 4566 auto converted to sql objects eg None -> NULL 4567 where: sql conditional parsed into a WHERE statement 4568 from_: sql statement parsed into a FROM statement 4569 dialect: the dialect used to parse the input expressions. 4570 **opts: other options to use to parse the input expressions. 4571 4572 Returns: 4573 Update: the syntax tree for the UPDATE statement. 4574 """ 4575 update_expr = Update(this=maybe_parse(table, into=Table, dialect=dialect)) 4576 update_expr.set( 4577 "expressions", 4578 [ 4579 EQ(this=maybe_parse(k, dialect=dialect, **opts), expression=convert(v)) 4580 for k, v in properties.items() 4581 ], 4582 ) 4583 if from_: 4584 update_expr.set( 4585 "from", 4586 maybe_parse(from_, into=From, dialect=dialect, prefix="FROM", **opts), 4587 ) 4588 if isinstance(where, Condition): 4589 where = Where(this=where) 4590 if where: 4591 update_expr.set( 4592 "where", 4593 maybe_parse(where, into=Where, dialect=dialect, prefix="WHERE", **opts), 4594 ) 4595 return update_expr 4596 4597 4598def delete( 4599 table: ExpOrStr, 4600 where: t.Optional[ExpOrStr] = None, 4601 returning: t.Optional[ExpOrStr] = None, 4602 dialect: DialectType = None, 4603 **opts, 4604) -> Delete: 4605 """ 4606 Builds a delete statement. 4607 4608 Example: 4609 >>> delete("my_table", where="id > 1").sql() 4610 'DELETE FROM my_table WHERE id > 1' 4611 4612 Args: 4613 where: sql conditional parsed into a WHERE statement 4614 returning: sql conditional parsed into a RETURNING statement 4615 dialect: the dialect used to parse the input expressions. 4616 **opts: other options to use to parse the input expressions. 4617 4618 Returns: 4619 Delete: the syntax tree for the DELETE statement. 4620 """ 4621 delete_expr = Delete().delete(table, dialect=dialect, copy=False, **opts) 4622 if where: 4623 delete_expr = delete_expr.where(where, dialect=dialect, copy=False, **opts) 4624 if returning: 4625 delete_expr = delete_expr.returning(returning, dialect=dialect, copy=False, **opts) 4626 return delete_expr 4627 4628 4629def condition(expression, dialect=None, **opts) -> Condition: 4630 """ 4631 Initialize a logical condition expression. 4632 4633 Example: 4634 >>> condition("x=1").sql() 4635 'x = 1' 4636 4637 This is helpful for composing larger logical syntax trees: 4638 >>> where = condition("x=1") 4639 >>> where = where.and_("y=1") 4640 >>> Select().from_("tbl").select("*").where(where).sql() 4641 'SELECT * FROM tbl WHERE x = 1 AND y = 1' 4642 4643 Args: 4644 *expression (str | Expression): the SQL code string to parse. 4645 If an Expression instance is passed, this is used as-is. 4646 dialect (str): the dialect used to parse the input expression (in the case that the 4647 input expression is a SQL string). 4648 **opts: other options to use to parse the input expressions (again, in the case 4649 that the input expression is a SQL string). 4650 4651 Returns: 4652 Condition: the expression 4653 """ 4654 return maybe_parse( # type: ignore 4655 expression, 4656 into=Condition, 4657 dialect=dialect, 4658 **opts, 4659 ) 4660 4661 4662def and_(*expressions, dialect=None, **opts) -> And: 4663 """ 4664 Combine multiple conditions with an AND logical operator. 4665 4666 Example: 4667 >>> and_("x=1", and_("y=1", "z=1")).sql() 4668 'x = 1 AND (y = 1 AND z = 1)' 4669 4670 Args: 4671 *expressions (str | Expression): the SQL code strings to parse. 4672 If an Expression instance is passed, this is used as-is. 4673 dialect (str): the dialect used to parse the input expression. 4674 **opts: other options to use to parse the input expressions. 4675 4676 Returns: 4677 And: the new condition 4678 """ 4679 return _combine(expressions, And, dialect, **opts) 4680 4681 4682def or_(*expressions, dialect=None, **opts) -> Or: 4683 """ 4684 Combine multiple conditions with an OR logical operator. 4685 4686 Example: 4687 >>> or_("x=1", or_("y=1", "z=1")).sql() 4688 'x = 1 OR (y = 1 OR z = 1)' 4689 4690 Args: 4691 *expressions (str | Expression): the SQL code strings to parse. 4692 If an Expression instance is passed, this is used as-is. 4693 dialect (str): the dialect used to parse the input expression. 4694 **opts: other options to use to parse the input expressions. 4695 4696 Returns: 4697 Or: the new condition 4698 """ 4699 return _combine(expressions, Or, dialect, **opts) 4700 4701 4702def not_(expression, dialect=None, **opts) -> Not: 4703 """ 4704 Wrap a condition with a NOT operator. 4705 4706 Example: 4707 >>> not_("this_suit='black'").sql() 4708 "NOT this_suit = 'black'" 4709 4710 Args: 4711 expression (str | Expression): the SQL code strings to parse. 4712 If an Expression instance is passed, this is used as-is. 4713 dialect (str): the dialect used to parse the input expression. 4714 **opts: other options to use to parse the input expressions. 4715 4716 Returns: 4717 Not: the new condition 4718 """ 4719 this = condition( 4720 expression, 4721 dialect=dialect, 4722 **opts, 4723 ) 4724 return Not(this=_wrap(this, Connector)) 4725 4726 4727def paren(expression) -> Paren: 4728 return Paren(this=expression) 4729 4730 4731SAFE_IDENTIFIER_RE = re.compile(r"^[_a-zA-Z][\w]*$") 4732 4733 4734@t.overload 4735def to_identifier(name: None, quoted: t.Optional[bool] = None) -> None: 4736 ... 4737 4738 4739@t.overload 4740def to_identifier(name: str | Identifier, quoted: t.Optional[bool] = None) -> Identifier: 4741 ... 4742 4743 4744def to_identifier(name, quoted=None): 4745 """Builds an identifier. 4746 4747 Args: 4748 name: The name to turn into an identifier. 4749 quoted: Whether or not force quote the identifier. 4750 4751 Returns: 4752 The identifier ast node. 4753 """ 4754 4755 if name is None: 4756 return None 4757 4758 if isinstance(name, Identifier): 4759 identifier = name 4760 elif isinstance(name, str): 4761 identifier = Identifier( 4762 this=name, 4763 quoted=not SAFE_IDENTIFIER_RE.match(name) if quoted is None else quoted, 4764 ) 4765 else: 4766 raise ValueError(f"Name needs to be a string or an Identifier, got: {name.__class__}") 4767 return identifier 4768 4769 4770INTERVAL_STRING_RE = re.compile(r"\s*([0-9]+)\s*([a-zA-Z]+)\s*") 4771 4772 4773def to_interval(interval: str | Literal) -> Interval: 4774 """Builds an interval expression from a string like '1 day' or '5 months'.""" 4775 if isinstance(interval, Literal): 4776 if not interval.is_string: 4777 raise ValueError("Invalid interval string.") 4778 4779 interval = interval.this 4780 4781 interval_parts = INTERVAL_STRING_RE.match(interval) # type: ignore 4782 4783 if not interval_parts: 4784 raise ValueError("Invalid interval string.") 4785 4786 return Interval( 4787 this=Literal.string(interval_parts.group(1)), 4788 unit=Var(this=interval_parts.group(2)), 4789 ) 4790 4791 4792@t.overload 4793def to_table(sql_path: str | Table, **kwargs) -> Table: 4794 ... 4795 4796 4797@t.overload 4798def to_table(sql_path: None, **kwargs) -> None: 4799 ... 4800 4801 4802def to_table(sql_path: t.Optional[str | Table], **kwargs) -> t.Optional[Table]: 4803 """ 4804 Create a table expression from a `[catalog].[schema].[table]` sql path. Catalog and schema are optional. 4805 If a table is passed in then that table is returned. 4806 4807 Args: 4808 sql_path: a `[catalog].[schema].[table]` string. 4809 4810 Returns: 4811 A table expression. 4812 """ 4813 if sql_path is None or isinstance(sql_path, Table): 4814 return sql_path 4815 if not isinstance(sql_path, str): 4816 raise ValueError(f"Invalid type provided for a table: {type(sql_path)}") 4817 4818 catalog, db, table_name = (to_identifier(x) for x in split_num_words(sql_path, ".", 3)) 4819 return Table(this=table_name, db=db, catalog=catalog, **kwargs) 4820 4821 4822def to_column(sql_path: str | Column, **kwargs) -> Column: 4823 """ 4824 Create a column from a `[table].[column]` sql path. Schema is optional. 4825 4826 If a column is passed in then that column is returned. 4827 4828 Args: 4829 sql_path: `[table].[column]` string 4830 Returns: 4831 Table: A column expression 4832 """ 4833 if sql_path is None or isinstance(sql_path, Column): 4834 return sql_path 4835 if not isinstance(sql_path, str): 4836 raise ValueError(f"Invalid type provided for column: {type(sql_path)}") 4837 return column(*reversed(sql_path.split(".")), **kwargs) # type: ignore 4838 4839 4840def alias_( 4841 expression: ExpOrStr, 4842 alias: str | Identifier, 4843 table: bool | t.Sequence[str | Identifier] = False, 4844 quoted: t.Optional[bool] = None, 4845 dialect: DialectType = None, 4846 **opts, 4847): 4848 """Create an Alias expression. 4849 4850 Example: 4851 >>> alias_('foo', 'bar').sql() 4852 'foo AS bar' 4853 4854 >>> alias_('(select 1, 2)', 'bar', table=['a', 'b']).sql() 4855 '(SELECT 1, 2) AS bar(a, b)' 4856 4857 Args: 4858 expression: the SQL code strings to parse. 4859 If an Expression instance is passed, this is used as-is. 4860 alias: the alias name to use. If the name has 4861 special characters it is quoted. 4862 table: Whether or not to create a table alias, can also be a list of columns. 4863 quoted: whether or not to quote the alias 4864 dialect: the dialect used to parse the input expression. 4865 **opts: other options to use to parse the input expressions. 4866 4867 Returns: 4868 Alias: the aliased expression 4869 """ 4870 exp = maybe_parse(expression, dialect=dialect, **opts) 4871 alias = to_identifier(alias, quoted=quoted) 4872 4873 if table: 4874 table_alias = TableAlias(this=alias) 4875 4876 exp = exp.copy() if isinstance(expression, Expression) else exp 4877 exp.set("alias", table_alias) 4878 4879 if not isinstance(table, bool): 4880 for column in table: 4881 table_alias.append("columns", to_identifier(column, quoted=quoted)) 4882 4883 return exp 4884 4885 # We don't set the "alias" arg for Window expressions, because that would add an IDENTIFIER node in 4886 # the AST, representing a "named_window" [1] construct (eg. bigquery). What we want is an ALIAS node 4887 # for the complete Window expression. 4888 # 4889 # [1]: https://cloud.google.com/bigquery/docs/reference/standard-sql/window-function-calls 4890 4891 if "alias" in exp.arg_types and not isinstance(exp, Window): 4892 exp = exp.copy() 4893 exp.set("alias", alias) 4894 return exp 4895 return Alias(this=exp, alias=alias) 4896 4897 4898def subquery(expression, alias=None, dialect=None, **opts): 4899 """ 4900 Build a subquery expression. 4901 4902 Example: 4903 >>> subquery('select x from tbl', 'bar').select('x').sql() 4904 'SELECT x FROM (SELECT x FROM tbl) AS bar' 4905 4906 Args: 4907 expression (str | Expression): the SQL code strings to parse. 4908 If an Expression instance is passed, this is used as-is. 4909 alias (str | Expression): the alias name to use. 4910 dialect (str): the dialect used to parse the input expression. 4911 **opts: other options to use to parse the input expressions. 4912 4913 Returns: 4914 Select: a new select with the subquery expression included 4915 """ 4916 4917 expression = maybe_parse(expression, dialect=dialect, **opts).subquery(alias) 4918 return Select().from_(expression, dialect=dialect, **opts) 4919 4920 4921def column( 4922 col: str | Identifier, 4923 table: t.Optional[str | Identifier] = None, 4924 db: t.Optional[str | Identifier] = None, 4925 catalog: t.Optional[str | Identifier] = None, 4926 quoted: t.Optional[bool] = None, 4927) -> Column: 4928 """ 4929 Build a Column. 4930 4931 Args: 4932 col: column name 4933 table: table name 4934 db: db name 4935 catalog: catalog name 4936 quoted: whether or not to force quote each part 4937 Returns: 4938 Column: column instance 4939 """ 4940 return Column( 4941 this=to_identifier(col, quoted=quoted), 4942 table=to_identifier(table, quoted=quoted), 4943 db=to_identifier(db, quoted=quoted), 4944 catalog=to_identifier(catalog, quoted=quoted), 4945 ) 4946 4947 4948def cast(expression: ExpOrStr, to: str | DataType | DataType.Type, **opts) -> Cast: 4949 """Cast an expression to a data type. 4950 4951 Example: 4952 >>> cast('x + 1', 'int').sql() 4953 'CAST(x + 1 AS INT)' 4954 4955 Args: 4956 expression: The expression to cast. 4957 to: The datatype to cast to. 4958 4959 Returns: 4960 A cast node. 4961 """ 4962 expression = maybe_parse(expression, **opts) 4963 return Cast(this=expression, to=DataType.build(to, **opts)) 4964 4965 4966def table_(table, db=None, catalog=None, quoted=None, alias=None) -> Table: 4967 """Build a Table. 4968 4969 Args: 4970 table (str | Expression): column name 4971 db (str | Expression): db name 4972 catalog (str | Expression): catalog name 4973 4974 Returns: 4975 Table: table instance 4976 """ 4977 return Table( 4978 this=to_identifier(table, quoted=quoted), 4979 db=to_identifier(db, quoted=quoted), 4980 catalog=to_identifier(catalog, quoted=quoted), 4981 alias=TableAlias(this=to_identifier(alias)) if alias else None, 4982 ) 4983 4984 4985def values( 4986 values: t.Iterable[t.Tuple[t.Any, ...]], 4987 alias: t.Optional[str] = None, 4988 columns: t.Optional[t.Iterable[str] | t.Dict[str, DataType]] = None, 4989) -> Values: 4990 """Build VALUES statement. 4991 4992 Example: 4993 >>> values([(1, '2')]).sql() 4994 "VALUES (1, '2')" 4995 4996 Args: 4997 values: values statements that will be converted to SQL 4998 alias: optional alias 4999 columns: Optional list of ordered column names or ordered dictionary of column names to types. 5000 If either are provided then an alias is also required. 5001 If a dictionary is provided then the first column of the values will be casted to the expected type 5002 in order to help with type inference. 5003 5004 Returns: 5005 Values: the Values expression object 5006 """ 5007 if columns and not alias: 5008 raise ValueError("Alias is required when providing columns") 5009 table_alias = ( 5010 TableAlias(this=to_identifier(alias), columns=[to_identifier(x) for x in columns]) 5011 if columns 5012 else TableAlias(this=to_identifier(alias) if alias else None) 5013 ) 5014 expressions = [convert(tup) for tup in values] 5015 if columns and isinstance(columns, dict): 5016 types = list(columns.values()) 5017 expressions[0].set( 5018 "expressions", 5019 [cast(x, types[i]) for i, x in enumerate(expressions[0].expressions)], 5020 ) 5021 return Values( 5022 expressions=expressions, 5023 alias=table_alias, 5024 ) 5025 5026 5027def var(name: t.Optional[ExpOrStr]) -> Var: 5028 """Build a SQL variable. 5029 5030 Example: 5031 >>> repr(var('x')) 5032 '(VAR this: x)' 5033 5034 >>> repr(var(column('x', table='y'))) 5035 '(VAR this: x)' 5036 5037 Args: 5038 name: The name of the var or an expression who's name will become the var. 5039 5040 Returns: 5041 The new variable node. 5042 """ 5043 if not name: 5044 raise ValueError("Cannot convert empty name into var.") 5045 5046 if isinstance(name, Expression): 5047 name = name.name 5048 return Var(this=name) 5049 5050 5051def rename_table(old_name: str | Table, new_name: str | Table) -> AlterTable: 5052 """Build ALTER TABLE... RENAME... expression 5053 5054 Args: 5055 old_name: The old name of the table 5056 new_name: The new name of the table 5057 5058 Returns: 5059 Alter table expression 5060 """ 5061 old_table = to_table(old_name) 5062 new_table = to_table(new_name) 5063 return AlterTable( 5064 this=old_table, 5065 actions=[ 5066 RenameTable(this=new_table), 5067 ], 5068 ) 5069 5070 5071def convert(value) -> Expression: 5072 """Convert a python value into an expression object. 5073 5074 Raises an error if a conversion is not possible. 5075 5076 Args: 5077 value (Any): a python object 5078 5079 Returns: 5080 Expression: the equivalent expression object 5081 """ 5082 if isinstance(value, Expression): 5083 return value 5084 if isinstance(value, str): 5085 return Literal.string(value) 5086 if isinstance(value, bool): 5087 return Boolean(this=value) 5088 if value is None or (isinstance(value, float) and math.isnan(value)): 5089 return NULL 5090 if isinstance(value, numbers.Number): 5091 return Literal.number(value) 5092 if isinstance(value, datetime.datetime): 5093 datetime_literal = Literal.string( 5094 (value if value.tzinfo else value.replace(tzinfo=datetime.timezone.utc)).isoformat() 5095 ) 5096 return TimeStrToTime(this=datetime_literal) 5097 if isinstance(value, datetime.date): 5098 date_literal = Literal.string(value.strftime("%Y-%m-%d")) 5099 return DateStrToDate(this=date_literal) 5100 if isinstance(value, tuple): 5101 return Tuple(expressions=[convert(v) for v in value]) 5102 if isinstance(value, list): 5103 return Array(expressions=[convert(v) for v in value]) 5104 if isinstance(value, dict): 5105 return Map( 5106 keys=[convert(k) for k in value], 5107 values=[convert(v) for v in value.values()], 5108 ) 5109 raise ValueError(f"Cannot convert {value}") 5110 5111 5112def replace_children(expression, fun, *args, **kwargs): 5113 """ 5114 Replace children of an expression with the result of a lambda fun(child) -> exp. 5115 """ 5116 for k, v in expression.args.items(): 5117 is_list_arg = type(v) is list 5118 5119 child_nodes = v if is_list_arg else [v] 5120 new_child_nodes = [] 5121 5122 for cn in child_nodes: 5123 if isinstance(cn, Expression): 5124 for child_node in ensure_collection(fun(cn, *args, **kwargs)): 5125 new_child_nodes.append(child_node) 5126 child_node.parent = expression 5127 child_node.arg_key = k 5128 else: 5129 new_child_nodes.append(cn) 5130 5131 expression.args[k] = new_child_nodes if is_list_arg else seq_get(new_child_nodes, 0) 5132 5133 5134def column_table_names(expression): 5135 """ 5136 Return all table names referenced through columns in an expression. 5137 5138 Example: 5139 >>> import sqlglot 5140 >>> column_table_names(sqlglot.parse_one("a.b AND c.d AND c.e")) 5141 ['c', 'a'] 5142 5143 Args: 5144 expression (sqlglot.Expression): expression to find table names 5145 5146 Returns: 5147 list: A list of unique names 5148 """ 5149 return list(dict.fromkeys(column.table for column in expression.find_all(Column))) 5150 5151 5152def table_name(table) -> str: 5153 """Get the full name of a table as a string. 5154 5155 Args: 5156 table (exp.Table | str): table expression node or string. 5157 5158 Examples: 5159 >>> from sqlglot import exp, parse_one 5160 >>> table_name(parse_one("select * from a.b.c").find(exp.Table)) 5161 'a.b.c' 5162 5163 Returns: 5164 The table name. 5165 """ 5166 5167 table = maybe_parse(table, into=Table) 5168 5169 if not table: 5170 raise ValueError(f"Cannot parse {table}") 5171 5172 return ".".join( 5173 part 5174 for part in ( 5175 table.text("catalog"), 5176 table.text("db"), 5177 table.name, 5178 ) 5179 if part 5180 ) 5181 5182 5183def replace_tables(expression, mapping): 5184 """Replace all tables in expression according to the mapping. 5185 5186 Args: 5187 expression (sqlglot.Expression): expression node to be transformed and replaced. 5188 mapping (Dict[str, str]): mapping of table names. 5189 5190 Examples: 5191 >>> from sqlglot import exp, parse_one 5192 >>> replace_tables(parse_one("select * from a.b"), {"a.b": "c"}).sql() 5193 'SELECT * FROM c' 5194 5195 Returns: 5196 The mapped expression. 5197 """ 5198 5199 def _replace_tables(node): 5200 if isinstance(node, Table): 5201 new_name = mapping.get(table_name(node)) 5202 if new_name: 5203 return to_table( 5204 new_name, 5205 **{k: v for k, v in node.args.items() if k not in ("this", "db", "catalog")}, 5206 ) 5207 return node 5208 5209 return expression.transform(_replace_tables) 5210 5211 5212def replace_placeholders(expression, *args, **kwargs): 5213 """Replace placeholders in an expression. 5214 5215 Args: 5216 expression (sqlglot.Expression): expression node to be transformed and replaced. 5217 args: positional names that will substitute unnamed placeholders in the given order. 5218 kwargs: keyword arguments that will substitute named placeholders. 5219 5220 Examples: 5221 >>> from sqlglot import exp, parse_one 5222 >>> replace_placeholders( 5223 ... parse_one("select * from :tbl where ? = ?"), 5224 ... exp.to_identifier("str_col"), "b", tbl=exp.to_identifier("foo") 5225 ... ).sql() 5226 "SELECT * FROM foo WHERE str_col = 'b'" 5227 5228 Returns: 5229 The mapped expression. 5230 """ 5231 5232 def _replace_placeholders(node, args, **kwargs): 5233 if isinstance(node, Placeholder): 5234 if node.name: 5235 new_name = kwargs.get(node.name) 5236 if new_name: 5237 return convert(new_name) 5238 else: 5239 try: 5240 return convert(next(args)) 5241 except StopIteration: 5242 pass 5243 return node 5244 5245 return expression.transform(_replace_placeholders, iter(args), **kwargs) 5246 5247 5248def expand( 5249 expression: Expression, sources: t.Dict[str, Subqueryable], copy: bool = True 5250) -> Expression: 5251 """Transforms an expression by expanding all referenced sources into subqueries. 5252 5253 Examples: 5254 >>> from sqlglot import parse_one 5255 >>> expand(parse_one("select * from x AS z"), {"x": parse_one("select * from y")}).sql() 5256 'SELECT * FROM (SELECT * FROM y) AS z /* source: x */' 5257 5258 >>> expand(parse_one("select * from x AS z"), {"x": parse_one("select * from y"), "y": parse_one("select * from z")}).sql() 5259 'SELECT * FROM (SELECT * FROM (SELECT * FROM z) AS y /* source: y */) AS z /* source: x */' 5260 5261 Args: 5262 expression: The expression to expand. 5263 sources: A dictionary of name to Subqueryables. 5264 copy: Whether or not to copy the expression during transformation. Defaults to True. 5265 5266 Returns: 5267 The transformed expression. 5268 """ 5269 5270 def _expand(node: Expression): 5271 if isinstance(node, Table): 5272 name = table_name(node) 5273 source = sources.get(name) 5274 if source: 5275 subquery = source.subquery(node.alias or name) 5276 subquery.comments = [f"source: {name}"] 5277 return subquery.transform(_expand, copy=False) 5278 return node 5279 5280 return expression.transform(_expand, copy=copy) 5281 5282 5283def func(name: str, *args, dialect: DialectType = None, **kwargs) -> Func: 5284 """ 5285 Returns a Func expression. 5286 5287 Examples: 5288 >>> func("abs", 5).sql() 5289 'ABS(5)' 5290 5291 >>> func("cast", this=5, to=DataType.build("DOUBLE")).sql() 5292 'CAST(5 AS DOUBLE)' 5293 5294 Args: 5295 name: the name of the function to build. 5296 args: the args used to instantiate the function of interest. 5297 dialect: the source dialect. 5298 kwargs: the kwargs used to instantiate the function of interest. 5299 5300 Note: 5301 The arguments `args` and `kwargs` are mutually exclusive. 5302 5303 Returns: 5304 An instance of the function of interest, or an anonymous function, if `name` doesn't 5305 correspond to an existing `sqlglot.expressions.Func` class. 5306 """ 5307 if args and kwargs: 5308 raise ValueError("Can't use both args and kwargs to instantiate a function.") 5309 5310 from sqlglot.dialects.dialect import Dialect 5311 5312 converted: t.List[Expression] = [maybe_parse(arg, dialect=dialect) for arg in args] 5313 kwargs = {key: maybe_parse(value, dialect=dialect) for key, value in kwargs.items()} 5314 5315 parser = Dialect.get_or_raise(dialect)().parser() 5316 from_args_list = parser.FUNCTIONS.get(name.upper()) 5317 5318 if from_args_list: 5319 function = from_args_list(converted) if converted else from_args_list.__self__(**kwargs) # type: ignore 5320 else: 5321 kwargs = kwargs or {"expressions": converted} 5322 function = Anonymous(this=name, **kwargs) 5323 5324 for error_message in function.error_messages(converted): 5325 raise ValueError(error_message) 5326 5327 return function 5328 5329 5330def true(): 5331 """ 5332 Returns a true Boolean expression. 5333 """ 5334 return Boolean(this=True) 5335 5336 5337def false(): 5338 """ 5339 Returns a false Boolean expression. 5340 """ 5341 return Boolean(this=False) 5342 5343 5344def null(): 5345 """ 5346 Returns a Null expression. 5347 """ 5348 return Null() 5349 5350 5351# TODO: deprecate this 5352TRUE = Boolean(this=True) 5353FALSE = Boolean(this=False) 5354NULL = Null()
57class Expression(metaclass=_Expression): 58 """ 59 The base class for all expressions in a syntax tree. Each Expression encapsulates any necessary 60 context, such as its child expressions, their names (arg keys), and whether a given child expression 61 is optional or not. 62 63 Attributes: 64 key: a unique key for each class in the Expression hierarchy. This is useful for hashing 65 and representing expressions as strings. 66 arg_types: determines what arguments (child nodes) are supported by an expression. It 67 maps arg keys to booleans that indicate whether the corresponding args are optional. 68 69 Example: 70 >>> class Foo(Expression): 71 ... arg_types = {"this": True, "expression": False} 72 73 The above definition informs us that Foo is an Expression that requires an argument called 74 "this" and may also optionally receive an argument called "expression". 75 76 Args: 77 args: a mapping used for retrieving the arguments of an expression, given their arg keys. 78 parent: a reference to the parent expression (or None, in case of root expressions). 79 arg_key: the arg key an expression is associated with, i.e. the name its parent expression 80 uses to refer to it. 81 comments: a list of comments that are associated with a given expression. This is used in 82 order to preserve comments when transpiling SQL code. 83 _type: the `sqlglot.expressions.DataType` type of an expression. This is inferred by the 84 optimizer, in order to enable some transformations that require type information. 85 """ 86 87 key = "expression" 88 arg_types = {"this": True} 89 __slots__ = ("args", "parent", "arg_key", "comments", "_type", "_meta", "_hash") 90 91 def __init__(self, **args: t.Any): 92 self.args: t.Dict[str, t.Any] = args 93 self.parent: t.Optional[Expression] = None 94 self.arg_key: t.Optional[str] = None 95 self.comments: t.Optional[t.List[str]] = None 96 self._type: t.Optional[DataType] = None 97 self._meta: t.Optional[t.Dict[str, t.Any]] = None 98 self._hash: t.Optional[int] = None 99 100 for arg_key, value in self.args.items(): 101 self._set_parent(arg_key, value) 102 103 def __eq__(self, other) -> bool: 104 return type(self) is type(other) and hash(self) == hash(other) 105 106 @property 107 def hashable_args(self) -> t.Any: 108 args = (self.args.get(k) for k in self.arg_types) 109 110 return tuple( 111 (tuple(_norm_arg(a) for a in arg) if arg else None) 112 if type(arg) is list 113 else (_norm_arg(arg) if arg is not None and arg is not False else None) 114 for arg in args 115 ) 116 117 def __hash__(self) -> int: 118 if self._hash is not None: 119 return self._hash 120 121 return hash((self.__class__, self.hashable_args)) 122 123 @property 124 def this(self): 125 """ 126 Retrieves the argument with key "this". 127 """ 128 return self.args.get("this") 129 130 @property 131 def expression(self): 132 """ 133 Retrieves the argument with key "expression". 134 """ 135 return self.args.get("expression") 136 137 @property 138 def expressions(self): 139 """ 140 Retrieves the argument with key "expressions". 141 """ 142 return self.args.get("expressions") or [] 143 144 def text(self, key) -> str: 145 """ 146 Returns a textual representation of the argument corresponding to "key". This can only be used 147 for args that are strings or leaf Expression instances, such as identifiers and literals. 148 """ 149 field = self.args.get(key) 150 if isinstance(field, str): 151 return field 152 if isinstance(field, (Identifier, Literal, Var)): 153 return field.this 154 if isinstance(field, (Star, Null)): 155 return field.name 156 return "" 157 158 @property 159 def is_string(self) -> bool: 160 """ 161 Checks whether a Literal expression is a string. 162 """ 163 return isinstance(self, Literal) and self.args["is_string"] 164 165 @property 166 def is_number(self) -> bool: 167 """ 168 Checks whether a Literal expression is a number. 169 """ 170 return isinstance(self, Literal) and not self.args["is_string"] 171 172 @property 173 def is_int(self) -> bool: 174 """ 175 Checks whether a Literal expression is an integer. 176 """ 177 if self.is_number: 178 try: 179 int(self.name) 180 return True 181 except ValueError: 182 pass 183 return False 184 185 @property 186 def is_star(self) -> bool: 187 """Checks whether an expression is a star.""" 188 return isinstance(self, Star) or (isinstance(self, Column) and isinstance(self.this, Star)) 189 190 @property 191 def alias(self) -> str: 192 """ 193 Returns the alias of the expression, or an empty string if it's not aliased. 194 """ 195 if isinstance(self.args.get("alias"), TableAlias): 196 return self.args["alias"].name 197 return self.text("alias") 198 199 @property 200 def name(self) -> str: 201 return self.text("this") 202 203 @property 204 def alias_or_name(self): 205 return self.alias or self.name 206 207 @property 208 def output_name(self): 209 """ 210 Name of the output column if this expression is a selection. 211 212 If the Expression has no output name, an empty string is returned. 213 214 Example: 215 >>> from sqlglot import parse_one 216 >>> parse_one("SELECT a").expressions[0].output_name 217 'a' 218 >>> parse_one("SELECT b AS c").expressions[0].output_name 219 'c' 220 >>> parse_one("SELECT 1 + 2").expressions[0].output_name 221 '' 222 """ 223 return "" 224 225 @property 226 def type(self) -> t.Optional[DataType]: 227 return self._type 228 229 @type.setter 230 def type(self, dtype: t.Optional[DataType | DataType.Type | str]) -> None: 231 if dtype and not isinstance(dtype, DataType): 232 dtype = DataType.build(dtype) 233 self._type = dtype # type: ignore 234 235 @property 236 def meta(self) -> t.Dict[str, t.Any]: 237 if self._meta is None: 238 self._meta = {} 239 return self._meta 240 241 def __deepcopy__(self, memo): 242 copy = self.__class__(**deepcopy(self.args)) 243 if self.comments is not None: 244 copy.comments = deepcopy(self.comments) 245 246 if self._type is not None: 247 copy._type = self._type.copy() 248 249 if self._meta is not None: 250 copy._meta = deepcopy(self._meta) 251 252 return copy 253 254 def copy(self): 255 """ 256 Returns a deep copy of the expression. 257 """ 258 new = deepcopy(self) 259 new.parent = self.parent 260 return new 261 262 def append(self, arg_key, value): 263 """ 264 Appends value to arg_key if it's a list or sets it as a new list. 265 266 Args: 267 arg_key (str): name of the list expression arg 268 value (Any): value to append to the list 269 """ 270 if not isinstance(self.args.get(arg_key), list): 271 self.args[arg_key] = [] 272 self.args[arg_key].append(value) 273 self._set_parent(arg_key, value) 274 275 def set(self, arg_key, value): 276 """ 277 Sets `arg_key` to `value`. 278 279 Args: 280 arg_key (str): name of the expression arg. 281 value: value to set the arg to. 282 """ 283 self.args[arg_key] = value 284 self._set_parent(arg_key, value) 285 286 def _set_parent(self, arg_key, value): 287 if hasattr(value, "parent"): 288 value.parent = self 289 value.arg_key = arg_key 290 elif type(value) is list: 291 for v in value: 292 if hasattr(v, "parent"): 293 v.parent = self 294 v.arg_key = arg_key 295 296 @property 297 def depth(self): 298 """ 299 Returns the depth of this tree. 300 """ 301 if self.parent: 302 return self.parent.depth + 1 303 return 0 304 305 def iter_expressions(self) -> t.Iterator[t.Tuple[str, Expression]]: 306 """Yields the key and expression for all arguments, exploding list args.""" 307 for k, vs in self.args.items(): 308 if type(vs) is list: 309 for v in vs: 310 if hasattr(v, "parent"): 311 yield k, v 312 else: 313 if hasattr(vs, "parent"): 314 yield k, vs 315 316 def find(self, *expression_types: t.Type[E], bfs=True) -> E | None: 317 """ 318 Returns the first node in this tree which matches at least one of 319 the specified types. 320 321 Args: 322 expression_types: the expression type(s) to match. 323 324 Returns: 325 The node which matches the criteria or None if no such node was found. 326 """ 327 return next(self.find_all(*expression_types, bfs=bfs), None) 328 329 def find_all(self, *expression_types: t.Type[E], bfs=True) -> t.Iterator[E]: 330 """ 331 Returns a generator object which visits all nodes in this tree and only 332 yields those that match at least one of the specified expression types. 333 334 Args: 335 expression_types: the expression type(s) to match. 336 337 Returns: 338 The generator object. 339 """ 340 for expression, *_ in self.walk(bfs=bfs): 341 if isinstance(expression, expression_types): 342 yield expression 343 344 def find_ancestor(self, *expression_types: t.Type[E]) -> E | None: 345 """ 346 Returns a nearest parent matching expression_types. 347 348 Args: 349 expression_types: the expression type(s) to match. 350 351 Returns: 352 The parent node. 353 """ 354 ancestor = self.parent 355 while ancestor and not isinstance(ancestor, expression_types): 356 ancestor = ancestor.parent 357 return t.cast(E, ancestor) 358 359 @property 360 def parent_select(self): 361 """ 362 Returns the parent select statement. 363 """ 364 return self.find_ancestor(Select) 365 366 @property 367 def same_parent(self): 368 """Returns if the parent is the same class as itself.""" 369 return type(self.parent) is self.__class__ 370 371 def root(self) -> Expression: 372 """ 373 Returns the root expression of this tree. 374 """ 375 expression = self 376 while expression.parent: 377 expression = expression.parent 378 return expression 379 380 def walk(self, bfs=True, prune=None): 381 """ 382 Returns a generator object which visits all nodes in this tree. 383 384 Args: 385 bfs (bool): if set to True the BFS traversal order will be applied, 386 otherwise the DFS traversal will be used instead. 387 prune ((node, parent, arg_key) -> bool): callable that returns True if 388 the generator should stop traversing this branch of the tree. 389 390 Returns: 391 the generator object. 392 """ 393 if bfs: 394 yield from self.bfs(prune=prune) 395 else: 396 yield from self.dfs(prune=prune) 397 398 def dfs(self, parent=None, key=None, prune=None): 399 """ 400 Returns a generator object which visits all nodes in this tree in 401 the DFS (Depth-first) order. 402 403 Returns: 404 The generator object. 405 """ 406 parent = parent or self.parent 407 yield self, parent, key 408 if prune and prune(self, parent, key): 409 return 410 411 for k, v in self.iter_expressions(): 412 yield from v.dfs(self, k, prune) 413 414 def bfs(self, prune=None): 415 """ 416 Returns a generator object which visits all nodes in this tree in 417 the BFS (Breadth-first) order. 418 419 Returns: 420 The generator object. 421 """ 422 queue = deque([(self, self.parent, None)]) 423 424 while queue: 425 item, parent, key = queue.popleft() 426 427 yield item, parent, key 428 if prune and prune(item, parent, key): 429 continue 430 431 for k, v in item.iter_expressions(): 432 queue.append((v, item, k)) 433 434 def unnest(self): 435 """ 436 Returns the first non parenthesis child or self. 437 """ 438 expression = self 439 while type(expression) is Paren: 440 expression = expression.this 441 return expression 442 443 def unalias(self): 444 """ 445 Returns the inner expression if this is an Alias. 446 """ 447 if isinstance(self, Alias): 448 return self.this 449 return self 450 451 def unnest_operands(self): 452 """ 453 Returns unnested operands as a tuple. 454 """ 455 return tuple(arg.unnest() for _, arg in self.iter_expressions()) 456 457 def flatten(self, unnest=True): 458 """ 459 Returns a generator which yields child nodes who's parents are the same class. 460 461 A AND B AND C -> [A, B, C] 462 """ 463 for node, _, _ in self.dfs(prune=lambda n, p, *_: p and not type(n) is self.__class__): 464 if not type(node) is self.__class__: 465 yield node.unnest() if unnest else node 466 467 def __str__(self): 468 return self.sql() 469 470 def __repr__(self): 471 return self._to_s() 472 473 def sql(self, dialect: DialectType = None, **opts) -> str: 474 """ 475 Returns SQL string representation of this tree. 476 477 Args: 478 dialect: the dialect of the output SQL string (eg. "spark", "hive", "presto", "mysql"). 479 opts: other `sqlglot.generator.Generator` options. 480 481 Returns: 482 The SQL string. 483 """ 484 from sqlglot.dialects import Dialect 485 486 return Dialect.get_or_raise(dialect)().generate(self, **opts) 487 488 def _to_s(self, hide_missing: bool = True, level: int = 0) -> str: 489 indent = "" if not level else "\n" 490 indent += "".join([" "] * level) 491 left = f"({self.key.upper()} " 492 493 args: t.Dict[str, t.Any] = { 494 k: ", ".join( 495 v._to_s(hide_missing=hide_missing, level=level + 1) 496 if hasattr(v, "_to_s") 497 else str(v) 498 for v in ensure_list(vs) 499 if v is not None 500 ) 501 for k, vs in self.args.items() 502 } 503 args["comments"] = self.comments 504 args["type"] = self.type 505 args = {k: v for k, v in args.items() if v or not hide_missing} 506 507 right = ", ".join(f"{k}: {v}" for k, v in args.items()) 508 right += ")" 509 510 return indent + left + right 511 512 def transform(self, fun, *args, copy=True, **kwargs): 513 """ 514 Recursively visits all tree nodes (excluding already transformed ones) 515 and applies the given transformation function to each node. 516 517 Args: 518 fun (function): a function which takes a node as an argument and returns a 519 new transformed node or the same node without modifications. If the function 520 returns None, then the corresponding node will be removed from the syntax tree. 521 copy (bool): if set to True a new tree instance is constructed, otherwise the tree is 522 modified in place. 523 524 Returns: 525 The transformed tree. 526 """ 527 node = self.copy() if copy else self 528 new_node = fun(node, *args, **kwargs) 529 530 if new_node is None or not isinstance(new_node, Expression): 531 return new_node 532 if new_node is not node: 533 new_node.parent = node.parent 534 return new_node 535 536 replace_children(new_node, lambda child: child.transform(fun, *args, copy=False, **kwargs)) 537 return new_node 538 539 def replace(self, expression): 540 """ 541 Swap out this expression with a new expression. 542 543 For example:: 544 545 >>> tree = Select().select("x").from_("tbl") 546 >>> tree.find(Column).replace(Column(this="y")) 547 (COLUMN this: y) 548 >>> tree.sql() 549 'SELECT y FROM tbl' 550 551 Args: 552 expression (Expression|None): new node 553 554 Returns: 555 The new expression or expressions. 556 """ 557 if not self.parent: 558 return expression 559 560 parent = self.parent 561 self.parent = None 562 563 replace_children(parent, lambda child: expression if child is self else child) 564 return expression 565 566 def pop(self): 567 """ 568 Remove this expression from its AST. 569 570 Returns: 571 The popped expression. 572 """ 573 self.replace(None) 574 return self 575 576 def assert_is(self, type_): 577 """ 578 Assert that this `Expression` is an instance of `type_`. 579 580 If it is NOT an instance of `type_`, this raises an assertion error. 581 Otherwise, this returns this expression. 582 583 Examples: 584 This is useful for type security in chained expressions: 585 586 >>> import sqlglot 587 >>> sqlglot.parse_one("SELECT x from y").assert_is(Select).select("z").sql() 588 'SELECT x, z FROM y' 589 """ 590 assert isinstance(self, type_) 591 return self 592 593 def error_messages(self, args: t.Optional[t.Sequence] = None) -> t.List[str]: 594 """ 595 Checks if this expression is valid (e.g. all mandatory args are set). 596 597 Args: 598 args: a sequence of values that were used to instantiate a Func expression. This is used 599 to check that the provided arguments don't exceed the function argument limit. 600 601 Returns: 602 A list of error messages for all possible errors that were found. 603 """ 604 errors: t.List[str] = [] 605 606 for k in self.args: 607 if k not in self.arg_types: 608 errors.append(f"Unexpected keyword: '{k}' for {self.__class__}") 609 for k, mandatory in self.arg_types.items(): 610 v = self.args.get(k) 611 if mandatory and (v is None or (isinstance(v, list) and not v)): 612 errors.append(f"Required keyword: '{k}' missing for {self.__class__}") 613 614 if ( 615 args 616 and isinstance(self, Func) 617 and len(args) > len(self.arg_types) 618 and not self.is_var_len_args 619 ): 620 errors.append( 621 f"The number of provided arguments ({len(args)}) is greater than " 622 f"the maximum number of supported arguments ({len(self.arg_types)})" 623 ) 624 625 return errors 626 627 def dump(self): 628 """ 629 Dump this Expression to a JSON-serializable dict. 630 """ 631 from sqlglot.serde import dump 632 633 return dump(self) 634 635 @classmethod 636 def load(cls, obj): 637 """ 638 Load a dict (as returned by `Expression.dump`) into an Expression instance. 639 """ 640 from sqlglot.serde import load 641 642 return load(obj)
The base class for all expressions in a syntax tree. Each Expression encapsulates any necessary context, such as its child expressions, their names (arg keys), and whether a given child expression is optional or not.
Attributes:
- key: a unique key for each class in the Expression hierarchy. This is useful for hashing and representing expressions as strings.
- arg_types: determines what arguments (child nodes) are supported by an expression. It maps arg keys to booleans that indicate whether the corresponding args are optional.
Example:
>>> class Foo(Expression): ... arg_types = {"this": True, "expression": False}The above definition informs us that Foo is an Expression that requires an argument called "this" and may also optionally receive an argument called "expression".
Arguments:
- args: a mapping used for retrieving the arguments of an expression, given their arg keys.
- parent: a reference to the parent expression (or None, in case of root expressions).
- arg_key: the arg key an expression is associated with, i.e. the name its parent expression uses to refer to it.
- comments: a list of comments that are associated with a given expression. This is used in order to preserve comments when transpiling SQL code.
- _type: the
sqlglot.expressions.DataTypetype of an expression. This is inferred by the optimizer, in order to enable some transformations that require type information.
91 def __init__(self, **args: t.Any): 92 self.args: t.Dict[str, t.Any] = args 93 self.parent: t.Optional[Expression] = None 94 self.arg_key: t.Optional[str] = None 95 self.comments: t.Optional[t.List[str]] = None 96 self._type: t.Optional[DataType] = None 97 self._meta: t.Optional[t.Dict[str, t.Any]] = None 98 self._hash: t.Optional[int] = None 99 100 for arg_key, value in self.args.items(): 101 self._set_parent(arg_key, value)
144 def text(self, key) -> str: 145 """ 146 Returns a textual representation of the argument corresponding to "key". This can only be used 147 for args that are strings or leaf Expression instances, such as identifiers and literals. 148 """ 149 field = self.args.get(key) 150 if isinstance(field, str): 151 return field 152 if isinstance(field, (Identifier, Literal, Var)): 153 return field.this 154 if isinstance(field, (Star, Null)): 155 return field.name 156 return ""
Returns a textual representation of the argument corresponding to "key". This can only be used for args that are strings or leaf Expression instances, such as identifiers and literals.
Name of the output column if this expression is a selection.
If the Expression has no output name, an empty string is returned.
Example:
>>> from sqlglot import parse_one >>> parse_one("SELECT a").expressions[0].output_name 'a' >>> parse_one("SELECT b AS c").expressions[0].output_name 'c' >>> parse_one("SELECT 1 + 2").expressions[0].output_name ''
254 def copy(self): 255 """ 256 Returns a deep copy of the expression. 257 """ 258 new = deepcopy(self) 259 new.parent = self.parent 260 return new
Returns a deep copy of the expression.
262 def append(self, arg_key, value): 263 """ 264 Appends value to arg_key if it's a list or sets it as a new list. 265 266 Args: 267 arg_key (str): name of the list expression arg 268 value (Any): value to append to the list 269 """ 270 if not isinstance(self.args.get(arg_key), list): 271 self.args[arg_key] = [] 272 self.args[arg_key].append(value) 273 self._set_parent(arg_key, value)
Appends value to arg_key if it's a list or sets it as a new list.
Arguments:
- arg_key (str): name of the list expression arg
- value (Any): value to append to the list
275 def set(self, arg_key, value): 276 """ 277 Sets `arg_key` to `value`. 278 279 Args: 280 arg_key (str): name of the expression arg. 281 value: value to set the arg to. 282 """ 283 self.args[arg_key] = value 284 self._set_parent(arg_key, value)
Sets arg_key to value.
Arguments:
- arg_key (str): name of the expression arg.
- value: value to set the arg to.
305 def iter_expressions(self) -> t.Iterator[t.Tuple[str, Expression]]: 306 """Yields the key and expression for all arguments, exploding list args.""" 307 for k, vs in self.args.items(): 308 if type(vs) is list: 309 for v in vs: 310 if hasattr(v, "parent"): 311 yield k, v 312 else: 313 if hasattr(vs, "parent"): 314 yield k, vs
Yields the key and expression for all arguments, exploding list args.
316 def find(self, *expression_types: t.Type[E], bfs=True) -> E | None: 317 """ 318 Returns the first node in this tree which matches at least one of 319 the specified types. 320 321 Args: 322 expression_types: the expression type(s) to match. 323 324 Returns: 325 The node which matches the criteria or None if no such node was found. 326 """ 327 return next(self.find_all(*expression_types, bfs=bfs), None)
Returns the first node in this tree which matches at least one of the specified types.
Arguments:
- expression_types: the expression type(s) to match.
Returns:
The node which matches the criteria or None if no such node was found.
329 def find_all(self, *expression_types: t.Type[E], bfs=True) -> t.Iterator[E]: 330 """ 331 Returns a generator object which visits all nodes in this tree and only 332 yields those that match at least one of the specified expression types. 333 334 Args: 335 expression_types: the expression type(s) to match. 336 337 Returns: 338 The generator object. 339 """ 340 for expression, *_ in self.walk(bfs=bfs): 341 if isinstance(expression, expression_types): 342 yield expression
Returns a generator object which visits all nodes in this tree and only yields those that match at least one of the specified expression types.
Arguments:
- expression_types: the expression type(s) to match.
Returns:
The generator object.
344 def find_ancestor(self, *expression_types: t.Type[E]) -> E | None: 345 """ 346 Returns a nearest parent matching expression_types. 347 348 Args: 349 expression_types: the expression type(s) to match. 350 351 Returns: 352 The parent node. 353 """ 354 ancestor = self.parent 355 while ancestor and not isinstance(ancestor, expression_types): 356 ancestor = ancestor.parent 357 return t.cast(E, ancestor)
Returns a nearest parent matching expression_types.
Arguments:
- expression_types: the expression type(s) to match.
Returns:
The parent node.
371 def root(self) -> Expression: 372 """ 373 Returns the root expression of this tree. 374 """ 375 expression = self 376 while expression.parent: 377 expression = expression.parent 378 return expression
Returns the root expression of this tree.
380 def walk(self, bfs=True, prune=None): 381 """ 382 Returns a generator object which visits all nodes in this tree. 383 384 Args: 385 bfs (bool): if set to True the BFS traversal order will be applied, 386 otherwise the DFS traversal will be used instead. 387 prune ((node, parent, arg_key) -> bool): callable that returns True if 388 the generator should stop traversing this branch of the tree. 389 390 Returns: 391 the generator object. 392 """ 393 if bfs: 394 yield from self.bfs(prune=prune) 395 else: 396 yield from self.dfs(prune=prune)
Returns a generator object which visits all nodes in this tree.
Arguments:
- bfs (bool): if set to True the BFS traversal order will be applied, otherwise the DFS traversal will be used instead.
- prune ((node, parent, arg_key) -> bool): callable that returns True if the generator should stop traversing this branch of the tree.
Returns:
the generator object.
398 def dfs(self, parent=None, key=None, prune=None): 399 """ 400 Returns a generator object which visits all nodes in this tree in 401 the DFS (Depth-first) order. 402 403 Returns: 404 The generator object. 405 """ 406 parent = parent or self.parent 407 yield self, parent, key 408 if prune and prune(self, parent, key): 409 return 410 411 for k, v in self.iter_expressions(): 412 yield from v.dfs(self, k, prune)
Returns a generator object which visits all nodes in this tree in the DFS (Depth-first) order.
Returns:
The generator object.
414 def bfs(self, prune=None): 415 """ 416 Returns a generator object which visits all nodes in this tree in 417 the BFS (Breadth-first) order. 418 419 Returns: 420 The generator object. 421 """ 422 queue = deque([(self, self.parent, None)]) 423 424 while queue: 425 item, parent, key = queue.popleft() 426 427 yield item, parent, key 428 if prune and prune(item, parent, key): 429 continue 430 431 for k, v in item.iter_expressions(): 432 queue.append((v, item, k))
Returns a generator object which visits all nodes in this tree in the BFS (Breadth-first) order.
Returns:
The generator object.
434 def unnest(self): 435 """ 436 Returns the first non parenthesis child or self. 437 """ 438 expression = self 439 while type(expression) is Paren: 440 expression = expression.this 441 return expression
Returns the first non parenthesis child or self.
443 def unalias(self): 444 """ 445 Returns the inner expression if this is an Alias. 446 """ 447 if isinstance(self, Alias): 448 return self.this 449 return self
Returns the inner expression if this is an Alias.
451 def unnest_operands(self): 452 """ 453 Returns unnested operands as a tuple. 454 """ 455 return tuple(arg.unnest() for _, arg in self.iter_expressions())
Returns unnested operands as a tuple.
457 def flatten(self, unnest=True): 458 """ 459 Returns a generator which yields child nodes who's parents are the same class. 460 461 A AND B AND C -> [A, B, C] 462 """ 463 for node, _, _ in self.dfs(prune=lambda n, p, *_: p and not type(n) is self.__class__): 464 if not type(node) is self.__class__: 465 yield node.unnest() if unnest else node
Returns a generator which yields child nodes who's parents are the same class.
A AND B AND C -> [A, B, C]
473 def sql(self, dialect: DialectType = None, **opts) -> str: 474 """ 475 Returns SQL string representation of this tree. 476 477 Args: 478 dialect: the dialect of the output SQL string (eg. "spark", "hive", "presto", "mysql"). 479 opts: other `sqlglot.generator.Generator` options. 480 481 Returns: 482 The SQL string. 483 """ 484 from sqlglot.dialects import Dialect 485 486 return Dialect.get_or_raise(dialect)().generate(self, **opts)
Returns SQL string representation of this tree.
Arguments:
- dialect: the dialect of the output SQL string (eg. "spark", "hive", "presto", "mysql").
- opts: other
sqlglot.generator.Generatoroptions.
Returns:
The SQL string.
512 def transform(self, fun, *args, copy=True, **kwargs): 513 """ 514 Recursively visits all tree nodes (excluding already transformed ones) 515 and applies the given transformation function to each node. 516 517 Args: 518 fun (function): a function which takes a node as an argument and returns a 519 new transformed node or the same node without modifications. If the function 520 returns None, then the corresponding node will be removed from the syntax tree. 521 copy (bool): if set to True a new tree instance is constructed, otherwise the tree is 522 modified in place. 523 524 Returns: 525 The transformed tree. 526 """ 527 node = self.copy() if copy else self 528 new_node = fun(node, *args, **kwargs) 529 530 if new_node is None or not isinstance(new_node, Expression): 531 return new_node 532 if new_node is not node: 533 new_node.parent = node.parent 534 return new_node 535 536 replace_children(new_node, lambda child: child.transform(fun, *args, copy=False, **kwargs)) 537 return new_node
Recursively visits all tree nodes (excluding already transformed ones) and applies the given transformation function to each node.
Arguments:
- fun (function): a function which takes a node as an argument and returns a new transformed node or the same node without modifications. If the function returns None, then the corresponding node will be removed from the syntax tree.
- copy (bool): if set to True a new tree instance is constructed, otherwise the tree is modified in place.
Returns:
The transformed tree.
539 def replace(self, expression): 540 """ 541 Swap out this expression with a new expression. 542 543 For example:: 544 545 >>> tree = Select().select("x").from_("tbl") 546 >>> tree.find(Column).replace(Column(this="y")) 547 (COLUMN this: y) 548 >>> tree.sql() 549 'SELECT y FROM tbl' 550 551 Args: 552 expression (Expression|None): new node 553 554 Returns: 555 The new expression or expressions. 556 """ 557 if not self.parent: 558 return expression 559 560 parent = self.parent 561 self.parent = None 562 563 replace_children(parent, lambda child: expression if child is self else child) 564 return expression
Swap out this expression with a new expression.
For example::
>>> tree = Select().select("x").from_("tbl")
>>> tree.find(Column).replace(Column(this="y"))
(COLUMN this: y)
>>> tree.sql()
'SELECT y FROM tbl'
Arguments:
- expression (Expression|None): new node
Returns:
The new expression or expressions.
566 def pop(self): 567 """ 568 Remove this expression from its AST. 569 570 Returns: 571 The popped expression. 572 """ 573 self.replace(None) 574 return self
Remove this expression from its AST.
Returns:
The popped expression.
576 def assert_is(self, type_): 577 """ 578 Assert that this `Expression` is an instance of `type_`. 579 580 If it is NOT an instance of `type_`, this raises an assertion error. 581 Otherwise, this returns this expression. 582 583 Examples: 584 This is useful for type security in chained expressions: 585 586 >>> import sqlglot 587 >>> sqlglot.parse_one("SELECT x from y").assert_is(Select).select("z").sql() 588 'SELECT x, z FROM y' 589 """ 590 assert isinstance(self, type_) 591 return self
Assert that this Expression is an instance of type_.
If it is NOT an instance of type_, this raises an assertion error.
Otherwise, this returns this expression.
Examples:
This is useful for type security in chained expressions:
>>> import sqlglot >>> sqlglot.parse_one("SELECT x from y").assert_is(Select).select("z").sql() 'SELECT x, z FROM y'
593 def error_messages(self, args: t.Optional[t.Sequence] = None) -> t.List[str]: 594 """ 595 Checks if this expression is valid (e.g. all mandatory args are set). 596 597 Args: 598 args: a sequence of values that were used to instantiate a Func expression. This is used 599 to check that the provided arguments don't exceed the function argument limit. 600 601 Returns: 602 A list of error messages for all possible errors that were found. 603 """ 604 errors: t.List[str] = [] 605 606 for k in self.args: 607 if k not in self.arg_types: 608 errors.append(f"Unexpected keyword: '{k}' for {self.__class__}") 609 for k, mandatory in self.arg_types.items(): 610 v = self.args.get(k) 611 if mandatory and (v is None or (isinstance(v, list) and not v)): 612 errors.append(f"Required keyword: '{k}' missing for {self.__class__}") 613 614 if ( 615 args 616 and isinstance(self, Func) 617 and len(args) > len(self.arg_types) 618 and not self.is_var_len_args 619 ): 620 errors.append( 621 f"The number of provided arguments ({len(args)}) is greater than " 622 f"the maximum number of supported arguments ({len(self.arg_types)})" 623 ) 624 625 return errors
Checks if this expression is valid (e.g. all mandatory args are set).
Arguments:
- args: a sequence of values that were used to instantiate a Func expression. This is used to check that the provided arguments don't exceed the function argument limit.
Returns:
A list of error messages for all possible errors that were found.
627 def dump(self): 628 """ 629 Dump this Expression to a JSON-serializable dict. 630 """ 631 from sqlglot.serde import dump 632 633 return dump(self)
Dump this Expression to a JSON-serializable dict.
635 @classmethod 636 def load(cls, obj): 637 """ 638 Load a dict (as returned by `Expression.dump`) into an Expression instance. 639 """ 640 from sqlglot.serde import load 641 642 return load(obj)
Load a dict (as returned by Expression.dump) into an Expression instance.
653class Condition(Expression): 654 def and_(self, *expressions, dialect=None, **opts): 655 """ 656 AND this condition with one or multiple expressions. 657 658 Example: 659 >>> condition("x=1").and_("y=1").sql() 660 'x = 1 AND y = 1' 661 662 Args: 663 *expressions (str | Expression): the SQL code strings to parse. 664 If an `Expression` instance is passed, it will be used as-is. 665 dialect (str): the dialect used to parse the input expression. 666 opts (kwargs): other options to use to parse the input expressions. 667 668 Returns: 669 And: the new condition. 670 """ 671 return and_(self, *expressions, dialect=dialect, **opts) 672 673 def or_(self, *expressions, dialect=None, **opts): 674 """ 675 OR this condition with one or multiple expressions. 676 677 Example: 678 >>> condition("x=1").or_("y=1").sql() 679 'x = 1 OR y = 1' 680 681 Args: 682 *expressions (str | Expression): the SQL code strings to parse. 683 If an `Expression` instance is passed, it will be used as-is. 684 dialect (str): the dialect used to parse the input expression. 685 opts (kwargs): other options to use to parse the input expressions. 686 687 Returns: 688 Or: the new condition. 689 """ 690 return or_(self, *expressions, dialect=dialect, **opts) 691 692 def not_(self): 693 """ 694 Wrap this condition with NOT. 695 696 Example: 697 >>> condition("x=1").not_().sql() 698 'NOT x = 1' 699 700 Returns: 701 Not: the new condition. 702 """ 703 return not_(self) 704 705 def _binop(self, klass: t.Type[E], other: ExpOrStr, reverse=False) -> E: 706 this = self 707 other = convert(other) 708 if not isinstance(this, klass) and not isinstance(other, klass): 709 this = _wrap(this, Binary) 710 other = _wrap(other, Binary) 711 if reverse: 712 return klass(this=other, expression=this) 713 return klass(this=this, expression=other) 714 715 def __getitem__(self, other: ExpOrStr | slice | t.Tuple[ExpOrStr]): 716 if isinstance(other, slice): 717 return Between( 718 this=self, 719 low=convert(other.start), 720 high=convert(other.stop), 721 ) 722 return Bracket(this=self, expressions=[convert(e) for e in ensure_list(other)]) 723 724 def isin(self, *expressions: ExpOrStr, query: t.Optional[ExpOrStr] = None, **opts) -> In: 725 return In( 726 this=self, 727 expressions=[convert(e) for e in expressions], 728 query=maybe_parse(query, **opts) if query else None, 729 ) 730 731 def like(self, other: ExpOrStr) -> Like: 732 return self._binop(Like, other) 733 734 def ilike(self, other: ExpOrStr) -> ILike: 735 return self._binop(ILike, other) 736 737 def eq(self, other: ExpOrStr) -> EQ: 738 return self._binop(EQ, other) 739 740 def neq(self, other: ExpOrStr) -> NEQ: 741 return self._binop(NEQ, other) 742 743 def rlike(self, other: ExpOrStr) -> RegexpLike: 744 return self._binop(RegexpLike, other) 745 746 def __lt__(self, other: ExpOrStr) -> LT: 747 return self._binop(LT, other) 748 749 def __le__(self, other: ExpOrStr) -> LTE: 750 return self._binop(LTE, other) 751 752 def __gt__(self, other: ExpOrStr) -> GT: 753 return self._binop(GT, other) 754 755 def __ge__(self, other: ExpOrStr) -> GTE: 756 return self._binop(GTE, other) 757 758 def __add__(self, other: ExpOrStr) -> Add: 759 return self._binop(Add, other) 760 761 def __radd__(self, other: ExpOrStr) -> Add: 762 return self._binop(Add, other, reverse=True) 763 764 def __sub__(self, other: ExpOrStr) -> Sub: 765 return self._binop(Sub, other) 766 767 def __rsub__(self, other: ExpOrStr) -> Sub: 768 return self._binop(Sub, other, reverse=True) 769 770 def __mul__(self, other: ExpOrStr) -> Mul: 771 return self._binop(Mul, other) 772 773 def __rmul__(self, other: ExpOrStr) -> Mul: 774 return self._binop(Mul, other, reverse=True) 775 776 def __truediv__(self, other: ExpOrStr) -> Div: 777 return self._binop(Div, other) 778 779 def __rtruediv__(self, other: ExpOrStr) -> Div: 780 return self._binop(Div, other, reverse=True) 781 782 def __floordiv__(self, other: ExpOrStr) -> IntDiv: 783 return self._binop(IntDiv, other) 784 785 def __rfloordiv__(self, other: ExpOrStr) -> IntDiv: 786 return self._binop(IntDiv, other, reverse=True) 787 788 def __mod__(self, other: ExpOrStr) -> Mod: 789 return self._binop(Mod, other) 790 791 def __rmod__(self, other: ExpOrStr) -> Mod: 792 return self._binop(Mod, other, reverse=True) 793 794 def __pow__(self, other: ExpOrStr) -> Pow: 795 return self._binop(Pow, other) 796 797 def __rpow__(self, other: ExpOrStr) -> Pow: 798 return self._binop(Pow, other, reverse=True) 799 800 def __and__(self, other: ExpOrStr) -> And: 801 return self._binop(And, other) 802 803 def __rand__(self, other: ExpOrStr) -> And: 804 return self._binop(And, other, reverse=True) 805 806 def __or__(self, other: ExpOrStr) -> Or: 807 return self._binop(Or, other) 808 809 def __ror__(self, other: ExpOrStr) -> Or: 810 return self._binop(Or, other, reverse=True) 811 812 def __neg__(self) -> Neg: 813 return Neg(this=_wrap(self, Binary)) 814 815 def __invert__(self) -> Not: 816 return not_(self)
654 def and_(self, *expressions, dialect=None, **opts): 655 """ 656 AND this condition with one or multiple expressions. 657 658 Example: 659 >>> condition("x=1").and_("y=1").sql() 660 'x = 1 AND y = 1' 661 662 Args: 663 *expressions (str | Expression): the SQL code strings to parse. 664 If an `Expression` instance is passed, it will be used as-is. 665 dialect (str): the dialect used to parse the input expression. 666 opts (kwargs): other options to use to parse the input expressions. 667 668 Returns: 669 And: the new condition. 670 """ 671 return and_(self, *expressions, dialect=dialect, **opts)
AND this condition with one or multiple expressions.
Example:
>>> condition("x=1").and_("y=1").sql() 'x = 1 AND y = 1'
Arguments:
- *expressions (str | Expression): the SQL code strings to parse.
If an
Expressioninstance is passed, it will be used as-is. - dialect (str): the dialect used to parse the input expression.
- opts (kwargs): other options to use to parse the input expressions.
Returns:
And: the new condition.
673 def or_(self, *expressions, dialect=None, **opts): 674 """ 675 OR this condition with one or multiple expressions. 676 677 Example: 678 >>> condition("x=1").or_("y=1").sql() 679 'x = 1 OR y = 1' 680 681 Args: 682 *expressions (str | Expression): the SQL code strings to parse. 683 If an `Expression` instance is passed, it will be used as-is. 684 dialect (str): the dialect used to parse the input expression. 685 opts (kwargs): other options to use to parse the input expressions. 686 687 Returns: 688 Or: the new condition. 689 """ 690 return or_(self, *expressions, dialect=dialect, **opts)
OR this condition with one or multiple expressions.
Example:
>>> condition("x=1").or_("y=1").sql() 'x = 1 OR y = 1'
Arguments:
- *expressions (str | Expression): the SQL code strings to parse.
If an
Expressioninstance is passed, it will be used as-is. - dialect (str): the dialect used to parse the input expression.
- opts (kwargs): other options to use to parse the input expressions.
Returns:
Or: the new condition.
692 def not_(self): 693 """ 694 Wrap this condition with NOT. 695 696 Example: 697 >>> condition("x=1").not_().sql() 698 'NOT x = 1' 699 700 Returns: 701 Not: the new condition. 702 """ 703 return not_(self)
Wrap this condition with NOT.
Example:
>>> condition("x=1").not_().sql() 'NOT x = 1'
Returns:
Not: the new condition.
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Relationships like x = y, x > 1, x >= y.
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
823class DerivedTable(Expression): 824 @property 825 def alias_column_names(self): 826 table_alias = self.args.get("alias") 827 if not table_alias: 828 return [] 829 column_list = table_alias.assert_is(TableAlias).args.get("columns") or [] 830 return [c.name for c in column_list] 831 832 @property 833 def selects(self): 834 alias = self.args.get("alias") 835 836 if alias: 837 return alias.columns 838 return [] 839 840 @property 841 def named_selects(self): 842 return [select.output_name for select in self.selects]
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
845class Unionable(Expression): 846 def union(self, expression, distinct=True, dialect=None, **opts): 847 """ 848 Builds a UNION expression. 849 850 Example: 851 >>> import sqlglot 852 >>> sqlglot.parse_one("SELECT * FROM foo").union("SELECT * FROM bla").sql() 853 'SELECT * FROM foo UNION SELECT * FROM bla' 854 855 Args: 856 expression (str | Expression): the SQL code string. 857 If an `Expression` instance is passed, it will be used as-is. 858 distinct (bool): set the DISTINCT flag if and only if this is true. 859 dialect (str): the dialect used to parse the input expression. 860 opts (kwargs): other options to use to parse the input expressions. 861 Returns: 862 Union: the Union expression. 863 """ 864 return union(left=self, right=expression, distinct=distinct, dialect=dialect, **opts) 865 866 def intersect(self, expression, distinct=True, dialect=None, **opts): 867 """ 868 Builds an INTERSECT expression. 869 870 Example: 871 >>> import sqlglot 872 >>> sqlglot.parse_one("SELECT * FROM foo").intersect("SELECT * FROM bla").sql() 873 'SELECT * FROM foo INTERSECT SELECT * FROM bla' 874 875 Args: 876 expression (str | Expression): the SQL code string. 877 If an `Expression` instance is passed, it will be used as-is. 878 distinct (bool): set the DISTINCT flag if and only if this is true. 879 dialect (str): the dialect used to parse the input expression. 880 opts (kwargs): other options to use to parse the input expressions. 881 Returns: 882 Intersect: the Intersect expression 883 """ 884 return intersect(left=self, right=expression, distinct=distinct, dialect=dialect, **opts) 885 886 def except_(self, expression, distinct=True, dialect=None, **opts): 887 """ 888 Builds an EXCEPT expression. 889 890 Example: 891 >>> import sqlglot 892 >>> sqlglot.parse_one("SELECT * FROM foo").except_("SELECT * FROM bla").sql() 893 'SELECT * FROM foo EXCEPT SELECT * FROM bla' 894 895 Args: 896 expression (str | Expression): the SQL code string. 897 If an `Expression` instance is passed, it will be used as-is. 898 distinct (bool): set the DISTINCT flag if and only if this is true. 899 dialect (str): the dialect used to parse the input expression. 900 opts (kwargs): other options to use to parse the input expressions. 901 Returns: 902 Except: the Except expression 903 """ 904 return except_(left=self, right=expression, distinct=distinct, dialect=dialect, **opts)
846 def union(self, expression, distinct=True, dialect=None, **opts): 847 """ 848 Builds a UNION expression. 849 850 Example: 851 >>> import sqlglot 852 >>> sqlglot.parse_one("SELECT * FROM foo").union("SELECT * FROM bla").sql() 853 'SELECT * FROM foo UNION SELECT * FROM bla' 854 855 Args: 856 expression (str | Expression): the SQL code string. 857 If an `Expression` instance is passed, it will be used as-is. 858 distinct (bool): set the DISTINCT flag if and only if this is true. 859 dialect (str): the dialect used to parse the input expression. 860 opts (kwargs): other options to use to parse the input expressions. 861 Returns: 862 Union: the Union expression. 863 """ 864 return union(left=self, right=expression, distinct=distinct, dialect=dialect, **opts)
Builds a UNION expression.
Example:
>>> import sqlglot >>> sqlglot.parse_one("SELECT * FROM foo").union("SELECT * FROM bla").sql() 'SELECT * FROM foo UNION SELECT * FROM bla'
Arguments:
- expression (str | Expression): the SQL code string.
If an
Expressioninstance is passed, it will be used as-is. - distinct (bool): set the DISTINCT flag if and only if this is true.
- dialect (str): the dialect used to parse the input expression.
- opts (kwargs): other options to use to parse the input expressions.
Returns:
Union: the Union expression.
866 def intersect(self, expression, distinct=True, dialect=None, **opts): 867 """ 868 Builds an INTERSECT expression. 869 870 Example: 871 >>> import sqlglot 872 >>> sqlglot.parse_one("SELECT * FROM foo").intersect("SELECT * FROM bla").sql() 873 'SELECT * FROM foo INTERSECT SELECT * FROM bla' 874 875 Args: 876 expression (str | Expression): the SQL code string. 877 If an `Expression` instance is passed, it will be used as-is. 878 distinct (bool): set the DISTINCT flag if and only if this is true. 879 dialect (str): the dialect used to parse the input expression. 880 opts (kwargs): other options to use to parse the input expressions. 881 Returns: 882 Intersect: the Intersect expression 883 """ 884 return intersect(left=self, right=expression, distinct=distinct, dialect=dialect, **opts)
Builds an INTERSECT expression.
Example:
>>> import sqlglot >>> sqlglot.parse_one("SELECT * FROM foo").intersect("SELECT * FROM bla").sql() 'SELECT * FROM foo INTERSECT SELECT * FROM bla'
Arguments:
- expression (str | Expression): the SQL code string.
If an
Expressioninstance is passed, it will be used as-is. - distinct (bool): set the DISTINCT flag if and only if this is true.
- dialect (str): the dialect used to parse the input expression.
- opts (kwargs): other options to use to parse the input expressions.
Returns:
Intersect: the Intersect expression
886 def except_(self, expression, distinct=True, dialect=None, **opts): 887 """ 888 Builds an EXCEPT expression. 889 890 Example: 891 >>> import sqlglot 892 >>> sqlglot.parse_one("SELECT * FROM foo").except_("SELECT * FROM bla").sql() 893 'SELECT * FROM foo EXCEPT SELECT * FROM bla' 894 895 Args: 896 expression (str | Expression): the SQL code string. 897 If an `Expression` instance is passed, it will be used as-is. 898 distinct (bool): set the DISTINCT flag if and only if this is true. 899 dialect (str): the dialect used to parse the input expression. 900 opts (kwargs): other options to use to parse the input expressions. 901 Returns: 902 Except: the Except expression 903 """ 904 return except_(left=self, right=expression, distinct=distinct, dialect=dialect, **opts)
Builds an EXCEPT expression.
Example:
>>> import sqlglot >>> sqlglot.parse_one("SELECT * FROM foo").except_("SELECT * FROM bla").sql() 'SELECT * FROM foo EXCEPT SELECT * FROM bla'
Arguments:
- expression (str | Expression): the SQL code string.
If an
Expressioninstance is passed, it will be used as-is. - distinct (bool): set the DISTINCT flag if and only if this is true.
- dialect (str): the dialect used to parse the input expression.
- opts (kwargs): other options to use to parse the input expressions.
Returns:
Except: the Except expression
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
911class Cache(Expression): 912 arg_types = { 913 "with": False, 914 "this": True, 915 "lazy": False, 916 "options": False, 917 "expression": False, 918 }
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
925class Create(Expression): 926 arg_types = { 927 "with": False, 928 "this": True, 929 "kind": True, 930 "expression": False, 931 "exists": False, 932 "properties": False, 933 "replace": False, 934 "unique": False, 935 "indexes": False, 936 "no_schema_binding": False, 937 "begin": False, 938 }
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
953class SetItem(Expression): 954 arg_types = { 955 "this": False, 956 "expressions": False, 957 "kind": False, 958 "collate": False, # MySQL SET NAMES statement 959 "global": False, 960 }
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
963class Show(Expression): 964 arg_types = { 965 "this": True, 966 "target": False, 967 "offset": False, 968 "limit": False, 969 "like": False, 970 "where": False, 971 "db": False, 972 "full": False, 973 "mutex": False, 974 "query": False, 975 "channel": False, 976 "global": False, 977 "log": False, 978 "position": False, 979 "types": False, 980 }
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
983class UserDefinedFunction(Expression): 984 arg_types = {"this": True, "expressions": False, "wrapped": False}
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
991class With(Expression): 992 arg_types = {"expressions": True, "recursive": False} 993 994 @property 995 def recursive(self) -> bool: 996 return bool(self.args.get("recursive"))
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
1007class TableAlias(Expression): 1008 arg_types = {"this": False, "columns": False} 1009 1010 @property 1011 def columns(self): 1012 return self.args.get("columns") or []
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
1027class Column(Condition): 1028 arg_types = {"this": True, "table": False, "db": False, "catalog": False, "join_mark": False} 1029 1030 @property 1031 def table(self) -> str: 1032 return self.text("table") 1033 1034 @property 1035 def db(self) -> str: 1036 return self.text("db") 1037 1038 @property 1039 def catalog(self) -> str: 1040 return self.text("catalog") 1041 1042 @property 1043 def output_name(self) -> str: 1044 return self.name 1045 1046 @property 1047 def parts(self) -> t.List[Identifier]: 1048 """Return the parts of a column in order catalog, db, table, name.""" 1049 return [part for part in reversed(list(self.args.values())) if part] 1050 1051 def to_dot(self) -> Dot: 1052 """Converts the column into a dot expression.""" 1053 parts = self.parts 1054 parent = self.parent 1055 1056 while parent: 1057 if isinstance(parent, Dot): 1058 parts.append(parent.expression) 1059 parent = parent.parent 1060 1061 return Dot.build(parts)
Name of the output column if this expression is a selection.
If the Expression has no output name, an empty string is returned.
Example:
>>> from sqlglot import parse_one >>> parse_one("SELECT a").expressions[0].output_name 'a' >>> parse_one("SELECT b AS c").expressions[0].output_name 'c' >>> parse_one("SELECT 1 + 2").expressions[0].output_name ''
Return the parts of a column in order catalog, db, table, name.
1051 def to_dot(self) -> Dot: 1052 """Converts the column into a dot expression.""" 1053 parts = self.parts 1054 parent = self.parent 1055 1056 while parent: 1057 if isinstance(parent, Dot): 1058 parts.append(parent.expression) 1059 parent = parent.parent 1060 1061 return Dot.build(parts)
Converts the column into a dot expression.
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
1068class ColumnDef(Expression): 1069 arg_types = { 1070 "this": True, 1071 "kind": False, 1072 "constraints": False, 1073 "exists": False, 1074 "position": False, 1075 }
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
1078class AlterColumn(Expression): 1079 arg_types = { 1080 "this": True, 1081 "dtype": False, 1082 "collate": False, 1083 "using": False, 1084 "default": False, 1085 "drop": False, 1086 }
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
1097class Comment(Expression): 1098 arg_types = {"this": True, "kind": True, "expression": True, "exists": False}
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
1149class GeneratedAsIdentityColumnConstraint(ColumnConstraintKind): 1150 # this: True -> ALWAYS, this: False -> BY DEFAULT 1151 arg_types = { 1152 "this": False, 1153 "start": False, 1154 "increment": False, 1155 "minvalue": False, 1156 "maxvalue": False, 1157 "cycle": False, 1158 }
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
1198class Delete(Expression): 1199 arg_types = {"with": False, "this": False, "using": False, "where": False, "returning": False} 1200 1201 def delete( 1202 self, 1203 table: ExpOrStr, 1204 dialect: DialectType = None, 1205 copy: bool = True, 1206 **opts, 1207 ) -> Delete: 1208 """ 1209 Create a DELETE expression or replace the table on an existing DELETE expression. 1210 1211 Example: 1212 >>> delete("tbl").sql() 1213 'DELETE FROM tbl' 1214 1215 Args: 1216 table: the table from which to delete. 1217 dialect: the dialect used to parse the input expression. 1218 copy: if `False`, modify this expression instance in-place. 1219 opts: other options to use to parse the input expressions. 1220 1221 Returns: 1222 Delete: the modified expression. 1223 """ 1224 return _apply_builder( 1225 expression=table, 1226 instance=self, 1227 arg="this", 1228 dialect=dialect, 1229 into=Table, 1230 copy=copy, 1231 **opts, 1232 ) 1233 1234 def where( 1235 self, 1236 *expressions: ExpOrStr, 1237 append: bool = True, 1238 dialect: DialectType = None, 1239 copy: bool = True, 1240 **opts, 1241 ) -> Delete: 1242 """ 1243 Append to or set the WHERE expressions. 1244 1245 Example: 1246 >>> delete("tbl").where("x = 'a' OR x < 'b'").sql() 1247 "DELETE FROM tbl WHERE x = 'a' OR x < 'b'" 1248 1249 Args: 1250 *expressions: the SQL code strings to parse. 1251 If an `Expression` instance is passed, it will be used as-is. 1252 Multiple expressions are combined with an AND operator. 1253 append: if `True`, AND the new expressions to any existing expression. 1254 Otherwise, this resets the expression. 1255 dialect: the dialect used to parse the input expressions. 1256 copy: if `False`, modify this expression instance in-place. 1257 opts: other options to use to parse the input expressions. 1258 1259 Returns: 1260 Delete: the modified expression. 1261 """ 1262 return _apply_conjunction_builder( 1263 *expressions, 1264 instance=self, 1265 arg="where", 1266 append=append, 1267 into=Where, 1268 dialect=dialect, 1269 copy=copy, 1270 **opts, 1271 ) 1272 1273 def returning( 1274 self, 1275 expression: ExpOrStr, 1276 dialect: DialectType = None, 1277 copy: bool = True, 1278 **opts, 1279 ) -> Delete: 1280 """ 1281 Set the RETURNING expression. Not supported by all dialects. 1282 1283 Example: 1284 >>> delete("tbl").returning("*", dialect="postgres").sql() 1285 'DELETE FROM tbl RETURNING *' 1286 1287 Args: 1288 expression: the SQL code strings to parse. 1289 If an `Expression` instance is passed, it will be used as-is. 1290 dialect: the dialect used to parse the input expressions. 1291 copy: if `False`, modify this expression instance in-place. 1292 opts: other options to use to parse the input expressions. 1293 1294 Returns: 1295 Delete: the modified expression. 1296 """ 1297 return _apply_builder( 1298 expression=expression, 1299 instance=self, 1300 arg="returning", 1301 prefix="RETURNING", 1302 dialect=dialect, 1303 copy=copy, 1304 into=Returning, 1305 **opts, 1306 )
1201 def delete( 1202 self, 1203 table: ExpOrStr, 1204 dialect: DialectType = None, 1205 copy: bool = True, 1206 **opts, 1207 ) -> Delete: 1208 """ 1209 Create a DELETE expression or replace the table on an existing DELETE expression. 1210 1211 Example: 1212 >>> delete("tbl").sql() 1213 'DELETE FROM tbl' 1214 1215 Args: 1216 table: the table from which to delete. 1217 dialect: the dialect used to parse the input expression. 1218 copy: if `False`, modify this expression instance in-place. 1219 opts: other options to use to parse the input expressions. 1220 1221 Returns: 1222 Delete: the modified expression. 1223 """ 1224 return _apply_builder( 1225 expression=table, 1226 instance=self, 1227 arg="this", 1228 dialect=dialect, 1229 into=Table, 1230 copy=copy, 1231 **opts, 1232 )
Create a DELETE expression or replace the table on an existing DELETE expression.
Example:
>>> delete("tbl").sql() 'DELETE FROM tbl'
Arguments:
- table: the table from which to delete.
- dialect: the dialect used to parse the input expression.
- copy: if
False, modify this expression instance in-place. - opts: other options to use to parse the input expressions.
Returns:
Delete: the modified expression.
1234 def where( 1235 self, 1236 *expressions: ExpOrStr, 1237 append: bool = True, 1238 dialect: DialectType = None, 1239 copy: bool = True, 1240 **opts, 1241 ) -> Delete: 1242 """ 1243 Append to or set the WHERE expressions. 1244 1245 Example: 1246 >>> delete("tbl").where("x = 'a' OR x < 'b'").sql() 1247 "DELETE FROM tbl WHERE x = 'a' OR x < 'b'" 1248 1249 Args: 1250 *expressions: the SQL code strings to parse. 1251 If an `Expression` instance is passed, it will be used as-is. 1252 Multiple expressions are combined with an AND operator. 1253 append: if `True`, AND the new expressions to any existing expression. 1254 Otherwise, this resets the expression. 1255 dialect: the dialect used to parse the input expressions. 1256 copy: if `False`, modify this expression instance in-place. 1257 opts: other options to use to parse the input expressions. 1258 1259 Returns: 1260 Delete: the modified expression. 1261 """ 1262 return _apply_conjunction_builder( 1263 *expressions, 1264 instance=self, 1265 arg="where", 1266 append=append, 1267 into=Where, 1268 dialect=dialect, 1269 copy=copy, 1270 **opts, 1271 )
Append to or set the WHERE expressions.
Example:
>>> delete("tbl").where("x = 'a' OR x < 'b'").sql() "DELETE FROM tbl WHERE x = 'a' OR x < 'b'"
Arguments:
- *expressions: the SQL code strings to parse.
If an
Expressioninstance is passed, it will be used as-is. Multiple expressions are combined with an AND operator. - append: if
True, AND the new expressions to any existing expression. Otherwise, this resets the expression. - dialect: the dialect used to parse the input expressions.
- copy: if
False, modify this expression instance in-place. - opts: other options to use to parse the input expressions.
Returns:
Delete: the modified expression.
1273 def returning( 1274 self, 1275 expression: ExpOrStr, 1276 dialect: DialectType = None, 1277 copy: bool = True, 1278 **opts, 1279 ) -> Delete: 1280 """ 1281 Set the RETURNING expression. Not supported by all dialects. 1282 1283 Example: 1284 >>> delete("tbl").returning("*", dialect="postgres").sql() 1285 'DELETE FROM tbl RETURNING *' 1286 1287 Args: 1288 expression: the SQL code strings to parse. 1289 If an `Expression` instance is passed, it will be used as-is. 1290 dialect: the dialect used to parse the input expressions. 1291 copy: if `False`, modify this expression instance in-place. 1292 opts: other options to use to parse the input expressions. 1293 1294 Returns: 1295 Delete: the modified expression. 1296 """ 1297 return _apply_builder( 1298 expression=expression, 1299 instance=self, 1300 arg="returning", 1301 prefix="RETURNING", 1302 dialect=dialect, 1303 copy=copy, 1304 into=Returning, 1305 **opts, 1306 )
Set the RETURNING expression. Not supported by all dialects.
Example:
>>> delete("tbl").returning("*", dialect="postgres").sql() 'DELETE FROM tbl RETURNING *'
Arguments:
- expression: the SQL code strings to parse.
If an
Expressioninstance is passed, it will be used as-is. - dialect: the dialect used to parse the input expressions.
- copy: if
False, modify this expression instance in-place. - opts: other options to use to parse the input expressions.
Returns:
Delete: the modified expression.
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
1309class Drop(Expression): 1310 arg_types = { 1311 "this": False, 1312 "kind": False, 1313 "exists": False, 1314 "temporary": False, 1315 "materialized": False, 1316 "cascade": False, 1317 "constraints": False, 1318 "purge": False, 1319 }
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
1330class Directory(Expression): 1331 # https://spark.apache.org/docs/3.0.0-preview/sql-ref-syntax-dml-insert-overwrite-directory-hive.html 1332 arg_types = {"this": True, "local": False, "row_format": False}
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
1335class ForeignKey(Expression): 1336 arg_types = { 1337 "expressions": True, 1338 "reference": False, 1339 "delete": False, 1340 "update": False, 1341 }
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
1374class Identifier(Expression): 1375 arg_types = {"this": True, "quoted": False} 1376 1377 @property 1378 def quoted(self): 1379 return bool(self.args.get("quoted")) 1380 1381 @property 1382 def hashable_args(self) -> t.Any: 1383 if self.quoted and any(char.isupper() for char in self.this): 1384 return (self.this, self.quoted) 1385 return self.this.lower() 1386 1387 @property 1388 def output_name(self): 1389 return self.name
Name of the output column if this expression is a selection.
If the Expression has no output name, an empty string is returned.
Example:
>>> from sqlglot import parse_one >>> parse_one("SELECT a").expressions[0].output_name 'a' >>> parse_one("SELECT b AS c").expressions[0].output_name 'c' >>> parse_one("SELECT 1 + 2").expressions[0].output_name ''
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
1392class Index(Expression): 1393 arg_types = { 1394 "this": False, 1395 "table": False, 1396 "where": False, 1397 "columns": False, 1398 "unique": False, 1399 "primary": False, 1400 "amp": False, # teradata 1401 }
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
1404class Insert(Expression): 1405 arg_types = { 1406 "with": False, 1407 "this": True, 1408 "expression": False, 1409 "conflict": False, 1410 "returning": False, 1411 "overwrite": False, 1412 "exists": False, 1413 "partition": False, 1414 "alternative": False, 1415 }
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
1418class OnConflict(Expression): 1419 arg_types = { 1420 "duplicate": False, 1421 "expressions": False, 1422 "nothing": False, 1423 "key": False, 1424 "constraint": False, 1425 }
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
1442class LoadData(Expression): 1443 arg_types = { 1444 "this": True, 1445 "local": False, 1446 "overwrite": False, 1447 "inpath": True, 1448 "partition": False, 1449 "input_format": False, 1450 "serde": False, 1451 }
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
1458class Fetch(Expression): 1459 arg_types = { 1460 "direction": False, 1461 "count": False, 1462 "percent": False, 1463 "with_ties": False, 1464 }
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
1467class Group(Expression): 1468 arg_types = { 1469 "expressions": False, 1470 "grouping_sets": False, 1471 "cube": False, 1472 "rollup": False, 1473 }
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
1484class Literal(Condition): 1485 arg_types = {"this": True, "is_string": True} 1486 1487 @property 1488 def hashable_args(self) -> t.Any: 1489 return (self.this, self.args.get("is_string")) 1490 1491 @classmethod 1492 def number(cls, number) -> Literal: 1493 return cls(this=str(number), is_string=False) 1494 1495 @classmethod 1496 def string(cls, string) -> Literal: 1497 return cls(this=str(string), is_string=True) 1498 1499 @property 1500 def output_name(self): 1501 return self.name
Name of the output column if this expression is a selection.
If the Expression has no output name, an empty string is returned.
Example:
>>> from sqlglot import parse_one >>> parse_one("SELECT a").expressions[0].output_name 'a' >>> parse_one("SELECT b AS c").expressions[0].output_name 'c' >>> parse_one("SELECT 1 + 2").expressions[0].output_name ''
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
1504class Join(Expression): 1505 arg_types = { 1506 "this": True, 1507 "on": False, 1508 "side": False, 1509 "kind": False, 1510 "using": False, 1511 "natural": False, 1512 "hint": False, 1513 } 1514 1515 @property 1516 def kind(self): 1517 return self.text("kind").upper() 1518 1519 @property 1520 def side(self): 1521 return self.text("side").upper() 1522 1523 @property 1524 def hint(self): 1525 return self.text("hint").upper() 1526 1527 @property 1528 def alias_or_name(self): 1529 return self.this.alias_or_name 1530 1531 def on(self, *expressions, append=True, dialect=None, copy=True, **opts): 1532 """ 1533 Append to or set the ON expressions. 1534 1535 Example: 1536 >>> import sqlglot 1537 >>> sqlglot.parse_one("JOIN x", into=Join).on("y = 1").sql() 1538 'JOIN x ON y = 1' 1539 1540 Args: 1541 *expressions (str | Expression): the SQL code strings to parse. 1542 If an `Expression` instance is passed, it will be used as-is. 1543 Multiple expressions are combined with an AND operator. 1544 append (bool): if `True`, AND the new expressions to any existing expression. 1545 Otherwise, this resets the expression. 1546 dialect (str): the dialect used to parse the input expressions. 1547 copy (bool): if `False`, modify this expression instance in-place. 1548 opts (kwargs): other options to use to parse the input expressions. 1549 1550 Returns: 1551 Join: the modified join expression. 1552 """ 1553 join = _apply_conjunction_builder( 1554 *expressions, 1555 instance=self, 1556 arg="on", 1557 append=append, 1558 dialect=dialect, 1559 copy=copy, 1560 **opts, 1561 ) 1562 1563 if join.kind == "CROSS": 1564 join.set("kind", None) 1565 1566 return join 1567 1568 def using(self, *expressions, append=True, dialect=None, copy=True, **opts): 1569 """ 1570 Append to or set the USING expressions. 1571 1572 Example: 1573 >>> import sqlglot 1574 >>> sqlglot.parse_one("JOIN x", into=Join).using("foo", "bla").sql() 1575 'JOIN x USING (foo, bla)' 1576 1577 Args: 1578 *expressions (str | Expression): the SQL code strings to parse. 1579 If an `Expression` instance is passed, it will be used as-is. 1580 append (bool): if `True`, concatenate the new expressions to the existing "using" list. 1581 Otherwise, this resets the expression. 1582 dialect (str): the dialect used to parse the input expressions. 1583 copy (bool): if `False`, modify this expression instance in-place. 1584 opts (kwargs): other options to use to parse the input expressions. 1585 1586 Returns: 1587 Join: the modified join expression. 1588 """ 1589 join = _apply_list_builder( 1590 *expressions, 1591 instance=self, 1592 arg="using", 1593 append=append, 1594 dialect=dialect, 1595 copy=copy, 1596 **opts, 1597 ) 1598 1599 if join.kind == "CROSS": 1600 join.set("kind", None) 1601 1602 return join
1531 def on(self, *expressions, append=True, dialect=None, copy=True, **opts): 1532 """ 1533 Append to or set the ON expressions. 1534 1535 Example: 1536 >>> import sqlglot 1537 >>> sqlglot.parse_one("JOIN x", into=Join).on("y = 1").sql() 1538 'JOIN x ON y = 1' 1539 1540 Args: 1541 *expressions (str | Expression): the SQL code strings to parse. 1542 If an `Expression` instance is passed, it will be used as-is. 1543 Multiple expressions are combined with an AND operator. 1544 append (bool): if `True`, AND the new expressions to any existing expression. 1545 Otherwise, this resets the expression. 1546 dialect (str): the dialect used to parse the input expressions. 1547 copy (bool): if `False`, modify this expression instance in-place. 1548 opts (kwargs): other options to use to parse the input expressions. 1549 1550 Returns: 1551 Join: the modified join expression. 1552 """ 1553 join = _apply_conjunction_builder( 1554 *expressions, 1555 instance=self, 1556 arg="on", 1557 append=append, 1558 dialect=dialect, 1559 copy=copy, 1560 **opts, 1561 ) 1562 1563 if join.kind == "CROSS": 1564 join.set("kind", None) 1565 1566 return join
Append to or set the ON expressions.
Example:
>>> import sqlglot >>> sqlglot.parse_one("JOIN x", into=Join).on("y = 1").sql() 'JOIN x ON y = 1'
Arguments:
- *expressions (str | Expression): the SQL code strings to parse.
If an
Expressioninstance is passed, it will be used as-is. Multiple expressions are combined with an AND operator. - append (bool): if
True, AND the new expressions to any existing expression. Otherwise, this resets the expression. - dialect (str): the dialect used to parse the input expressions.
- copy (bool): if
False, modify this expression instance in-place. - opts (kwargs): other options to use to parse the input expressions.
Returns:
Join: the modified join expression.
1568 def using(self, *expressions, append=True, dialect=None, copy=True, **opts): 1569 """ 1570 Append to or set the USING expressions. 1571 1572 Example: 1573 >>> import sqlglot 1574 >>> sqlglot.parse_one("JOIN x", into=Join).using("foo", "bla").sql() 1575 'JOIN x USING (foo, bla)' 1576 1577 Args: 1578 *expressions (str | Expression): the SQL code strings to parse. 1579 If an `Expression` instance is passed, it will be used as-is. 1580 append (bool): if `True`, concatenate the new expressions to the existing "using" list. 1581 Otherwise, this resets the expression. 1582 dialect (str): the dialect used to parse the input expressions. 1583 copy (bool): if `False`, modify this expression instance in-place. 1584 opts (kwargs): other options to use to parse the input expressions. 1585 1586 Returns: 1587 Join: the modified join expression. 1588 """ 1589 join = _apply_list_builder( 1590 *expressions, 1591 instance=self, 1592 arg="using", 1593 append=append, 1594 dialect=dialect, 1595 copy=copy, 1596 **opts, 1597 ) 1598 1599 if join.kind == "CROSS": 1600 join.set("kind", None) 1601 1602 return join
Append to or set the USING expressions.
Example:
>>> import sqlglot >>> sqlglot.parse_one("JOIN x", into=Join).using("foo", "bla").sql() 'JOIN x USING (foo, bla)'
Arguments:
- *expressions (str | Expression): the SQL code strings to parse.
If an
Expressioninstance is passed, it will be used as-is. - append (bool): if
True, concatenate the new expressions to the existing "using" list. Otherwise, this resets the expression. - dialect (str): the dialect used to parse the input expressions.
- copy (bool): if
False, modify this expression instance in-place. - opts (kwargs): other options to use to parse the input expressions.
Returns:
Join: the modified join expression.
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
1605class Lateral(UDTF): 1606 arg_types = {"this": True, "view": False, "outer": False, "alias": False}
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
1609class MatchRecognize(Expression): 1610 arg_types = { 1611 "partition_by": False, 1612 "order": False, 1613 "measures": False, 1614 "rows": False, 1615 "after": False, 1616 "pattern": False, 1617 "define": False, 1618 "alias": False, 1619 }
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
1658class AfterJournalProperty(Property): 1659 arg_types = {"no": True, "dual": False, "local": False}
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
1670class BlockCompressionProperty(Property): 1671 arg_types = {"autotemp": False, "always": False, "default": True, "manual": True, "never": True}
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
1686class DataBlocksizeProperty(Property): 1687 arg_types = {"size": False, "units": False, "min": False, "default": False}
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
1726class InputOutputFormat(Expression): 1727 arg_types = {"input_format": False, "output_format": False}
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
1730class IsolatedLoadingProperty(Property): 1731 arg_types = { 1732 "no": True, 1733 "concurrent": True, 1734 "for_all": True, 1735 "for_insert": True, 1736 "for_none": True, 1737 }
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
1756class LockingProperty(Property): 1757 arg_types = { 1758 "this": False, 1759 "kind": True, 1760 "for_or_in": True, 1761 "lock_type": True, 1762 "override": False, 1763 }
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
1774class MergeBlockRatioProperty(Property): 1775 arg_types = {"this": False, "no": False, "default": False, "percent": False}
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
1790class ReturnsProperty(Property): 1791 arg_types = {"this": True, "is_table": False, "table": False}
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
1798class RowFormatDelimitedProperty(Property): 1799 # https://cwiki.apache.org/confluence/display/hive/languagemanual+dml 1800 arg_types = { 1801 "fields": False, 1802 "escaped": False, 1803 "collection_items": False, 1804 "map_keys": False, 1805 "lines": False, 1806 "null": False, 1807 "serde": False, 1808 }
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
1863class Properties(Expression): 1864 arg_types = {"expressions": True} 1865 1866 NAME_TO_PROPERTY = { 1867 "ALGORITHM": AlgorithmProperty, 1868 "AUTO_INCREMENT": AutoIncrementProperty, 1869 "CHARACTER SET": CharacterSetProperty, 1870 "COLLATE": CollateProperty, 1871 "COMMENT": SchemaCommentProperty, 1872 "DEFINER": DefinerProperty, 1873 "DISTKEY": DistKeyProperty, 1874 "DISTSTYLE": DistStyleProperty, 1875 "ENGINE": EngineProperty, 1876 "EXECUTE AS": ExecuteAsProperty, 1877 "FORMAT": FileFormatProperty, 1878 "LANGUAGE": LanguageProperty, 1879 "LOCATION": LocationProperty, 1880 "PARTITIONED_BY": PartitionedByProperty, 1881 "RETURNS": ReturnsProperty, 1882 "ROW_FORMAT": RowFormatProperty, 1883 "SORTKEY": SortKeyProperty, 1884 "TABLE_FORMAT": TableFormatProperty, 1885 } 1886 1887 PROPERTY_TO_NAME = {v: k for k, v in NAME_TO_PROPERTY.items()} 1888 1889 # CREATE property locations 1890 # Form: schema specified 1891 # create [POST_CREATE] 1892 # table a [POST_NAME] 1893 # (b int) [POST_SCHEMA] 1894 # with ([POST_WITH]) 1895 # index (b) [POST_INDEX] 1896 # 1897 # Form: alias selection 1898 # create [POST_CREATE] 1899 # table a [POST_NAME] 1900 # as [POST_ALIAS] (select * from b) [POST_EXPRESSION] 1901 # index (c) [POST_INDEX] 1902 class Location(AutoName): 1903 POST_CREATE = auto() 1904 POST_NAME = auto() 1905 POST_SCHEMA = auto() 1906 POST_WITH = auto() 1907 POST_ALIAS = auto() 1908 POST_EXPRESSION = auto() 1909 POST_INDEX = auto() 1910 UNSUPPORTED = auto() 1911 1912 @classmethod 1913 def from_dict(cls, properties_dict) -> Properties: 1914 expressions = [] 1915 for key, value in properties_dict.items(): 1916 property_cls = cls.NAME_TO_PROPERTY.get(key.upper()) 1917 if property_cls: 1918 expressions.append(property_cls(this=convert(value))) 1919 else: 1920 expressions.append(Property(this=Literal.string(key), value=convert(value))) 1921 1922 return cls(expressions=expressions)
1912 @classmethod 1913 def from_dict(cls, properties_dict) -> Properties: 1914 expressions = [] 1915 for key, value in properties_dict.items(): 1916 property_cls = cls.NAME_TO_PROPERTY.get(key.upper()) 1917 if property_cls: 1918 expressions.append(property_cls(this=convert(value))) 1919 else: 1920 expressions.append(Property(this=Literal.string(key), value=convert(value))) 1921 1922 return cls(expressions=expressions)
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
1902 class Location(AutoName): 1903 POST_CREATE = auto() 1904 POST_NAME = auto() 1905 POST_SCHEMA = auto() 1906 POST_WITH = auto() 1907 POST_ALIAS = auto() 1908 POST_EXPRESSION = auto() 1909 POST_INDEX = auto() 1910 UNSUPPORTED = auto()
An enumeration.
Inherited Members
- enum.Enum
- name
- value
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
1934class Reference(Expression): 1935 arg_types = {"this": True, "expressions": False, "options": False}
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
1942class Subqueryable(Unionable): 1943 def subquery(self, alias=None, copy=True) -> Subquery: 1944 """ 1945 Convert this expression to an aliased expression that can be used as a Subquery. 1946 1947 Example: 1948 >>> subquery = Select().select("x").from_("tbl").subquery() 1949 >>> Select().select("x").from_(subquery).sql() 1950 'SELECT x FROM (SELECT x FROM tbl)' 1951 1952 Args: 1953 alias (str | Identifier): an optional alias for the subquery 1954 copy (bool): if `False`, modify this expression instance in-place. 1955 1956 Returns: 1957 Alias: the subquery 1958 """ 1959 instance = _maybe_copy(self, copy) 1960 return Subquery( 1961 this=instance, 1962 alias=TableAlias(this=to_identifier(alias)) if alias else None, 1963 ) 1964 1965 def limit(self, expression, dialect=None, copy=True, **opts) -> Select: 1966 raise NotImplementedError 1967 1968 @property 1969 def ctes(self): 1970 with_ = self.args.get("with") 1971 if not with_: 1972 return [] 1973 return with_.expressions 1974 1975 @property 1976 def selects(self): 1977 raise NotImplementedError("Subqueryable objects must implement `selects`") 1978 1979 @property 1980 def named_selects(self): 1981 raise NotImplementedError("Subqueryable objects must implement `named_selects`") 1982 1983 def with_( 1984 self, 1985 alias, 1986 as_, 1987 recursive=None, 1988 append=True, 1989 dialect=None, 1990 copy=True, 1991 **opts, 1992 ): 1993 """ 1994 Append to or set the common table expressions. 1995 1996 Example: 1997 >>> Select().with_("tbl2", as_="SELECT * FROM tbl").select("x").from_("tbl2").sql() 1998 'WITH tbl2 AS (SELECT * FROM tbl) SELECT x FROM tbl2' 1999 2000 Args: 2001 alias (str | Expression): the SQL code string to parse as the table name. 2002 If an `Expression` instance is passed, this is used as-is. 2003 as_ (str | Expression): the SQL code string to parse as the table expression. 2004 If an `Expression` instance is passed, it will be used as-is. 2005 recursive (bool): set the RECURSIVE part of the expression. Defaults to `False`. 2006 append (bool): if `True`, add to any existing expressions. 2007 Otherwise, this resets the expressions. 2008 dialect (str): the dialect used to parse the input expression. 2009 copy (bool): if `False`, modify this expression instance in-place. 2010 opts (kwargs): other options to use to parse the input expressions. 2011 2012 Returns: 2013 Select: the modified expression. 2014 """ 2015 alias_expression = maybe_parse( 2016 alias, 2017 dialect=dialect, 2018 into=TableAlias, 2019 **opts, 2020 ) 2021 as_expression = maybe_parse( 2022 as_, 2023 dialect=dialect, 2024 **opts, 2025 ) 2026 cte = CTE( 2027 this=as_expression, 2028 alias=alias_expression, 2029 ) 2030 return _apply_child_list_builder( 2031 cte, 2032 instance=self, 2033 arg="with", 2034 append=append, 2035 copy=copy, 2036 into=With, 2037 properties={"recursive": recursive or False}, 2038 )
1943 def subquery(self, alias=None, copy=True) -> Subquery: 1944 """ 1945 Convert this expression to an aliased expression that can be used as a Subquery. 1946 1947 Example: 1948 >>> subquery = Select().select("x").from_("tbl").subquery() 1949 >>> Select().select("x").from_(subquery).sql() 1950 'SELECT x FROM (SELECT x FROM tbl)' 1951 1952 Args: 1953 alias (str | Identifier): an optional alias for the subquery 1954 copy (bool): if `False`, modify this expression instance in-place. 1955 1956 Returns: 1957 Alias: the subquery 1958 """ 1959 instance = _maybe_copy(self, copy) 1960 return Subquery( 1961 this=instance, 1962 alias=TableAlias(this=to_identifier(alias)) if alias else None, 1963 )
Convert this expression to an aliased expression that can be used as a Subquery.
Example:
>>> subquery = Select().select("x").from_("tbl").subquery() >>> Select().select("x").from_(subquery).sql() 'SELECT x FROM (SELECT x FROM tbl)'
Arguments:
- alias (str | Identifier): an optional alias for the subquery
- copy (bool): if
False, modify this expression instance in-place.
Returns:
Alias: the subquery
1983 def with_( 1984 self, 1985 alias, 1986 as_, 1987 recursive=None, 1988 append=True, 1989 dialect=None, 1990 copy=True, 1991 **opts, 1992 ): 1993 """ 1994 Append to or set the common table expressions. 1995 1996 Example: 1997 >>> Select().with_("tbl2", as_="SELECT * FROM tbl").select("x").from_("tbl2").sql() 1998 'WITH tbl2 AS (SELECT * FROM tbl) SELECT x FROM tbl2' 1999 2000 Args: 2001 alias (str | Expression): the SQL code string to parse as the table name. 2002 If an `Expression` instance is passed, this is used as-is. 2003 as_ (str | Expression): the SQL code string to parse as the table expression. 2004 If an `Expression` instance is passed, it will be used as-is. 2005 recursive (bool): set the RECURSIVE part of the expression. Defaults to `False`. 2006 append (bool): if `True`, add to any existing expressions. 2007 Otherwise, this resets the expressions. 2008 dialect (str): the dialect used to parse the input expression. 2009 copy (bool): if `False`, modify this expression instance in-place. 2010 opts (kwargs): other options to use to parse the input expressions. 2011 2012 Returns: 2013 Select: the modified expression. 2014 """ 2015 alias_expression = maybe_parse( 2016 alias, 2017 dialect=dialect, 2018 into=TableAlias, 2019 **opts, 2020 ) 2021 as_expression = maybe_parse( 2022 as_, 2023 dialect=dialect, 2024 **opts, 2025 ) 2026 cte = CTE( 2027 this=as_expression, 2028 alias=alias_expression, 2029 ) 2030 return _apply_child_list_builder( 2031 cte, 2032 instance=self, 2033 arg="with", 2034 append=append, 2035 copy=copy, 2036 into=With, 2037 properties={"recursive": recursive or False}, 2038 )
Append to or set the common table expressions.
Example:
>>> Select().with_("tbl2", as_="SELECT * FROM tbl").select("x").from_("tbl2").sql() 'WITH tbl2 AS (SELECT * FROM tbl) SELECT x FROM tbl2'
Arguments:
- alias (str | Expression): the SQL code string to parse as the table name.
If an
Expressioninstance is passed, this is used as-is. - as_ (str | Expression): the SQL code string to parse as the table expression.
If an
Expressioninstance is passed, it will be used as-is. - recursive (bool): set the RECURSIVE part of the expression. Defaults to
False. - append (bool): if
True, add to any existing expressions. Otherwise, this resets the expressions. - dialect (str): the dialect used to parse the input expression.
- copy (bool): if
False, modify this expression instance in-place. - opts (kwargs): other options to use to parse the input expressions.
Returns:
Select: the modified expression.
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
2062class Table(Expression): 2063 arg_types = { 2064 "this": True, 2065 "alias": False, 2066 "db": False, 2067 "catalog": False, 2068 "laterals": False, 2069 "joins": False, 2070 "pivots": False, 2071 "hints": False, 2072 "system_time": False, 2073 } 2074 2075 @property 2076 def db(self) -> str: 2077 return self.text("db") 2078 2079 @property 2080 def catalog(self) -> str: 2081 return self.text("catalog")
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
2085class SystemTime(Expression): 2086 arg_types = { 2087 "this": False, 2088 "expression": False, 2089 "kind": True, 2090 }
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
2093class Union(Subqueryable): 2094 arg_types = { 2095 "with": False, 2096 "this": True, 2097 "expression": True, 2098 "distinct": False, 2099 **QUERY_MODIFIERS, 2100 } 2101 2102 def limit(self, expression, dialect=None, copy=True, **opts) -> Select: 2103 """ 2104 Set the LIMIT expression. 2105 2106 Example: 2107 >>> select("1").union(select("1")).limit(1).sql() 2108 'SELECT * FROM (SELECT 1 UNION SELECT 1) AS _l_0 LIMIT 1' 2109 2110 Args: 2111 expression (str | int | Expression): the SQL code string to parse. 2112 This can also be an integer. 2113 If a `Limit` instance is passed, this is used as-is. 2114 If another `Expression` instance is passed, it will be wrapped in a `Limit`. 2115 dialect (str): the dialect used to parse the input expression. 2116 copy (bool): if `False`, modify this expression instance in-place. 2117 opts (kwargs): other options to use to parse the input expressions. 2118 2119 Returns: 2120 Select: The limited subqueryable. 2121 """ 2122 return ( 2123 select("*") 2124 .from_(self.subquery(alias="_l_0", copy=copy)) 2125 .limit(expression, dialect=dialect, copy=False, **opts) 2126 ) 2127 2128 def select( 2129 self, 2130 *expressions: ExpOrStr, 2131 append: bool = True, 2132 dialect: DialectType = None, 2133 copy: bool = True, 2134 **opts, 2135 ) -> Union: 2136 """Append to or set the SELECT of the union recursively. 2137 2138 Example: 2139 >>> from sqlglot import parse_one 2140 >>> parse_one("select a from x union select a from y union select a from z").select("b").sql() 2141 'SELECT a, b FROM x UNION SELECT a, b FROM y UNION SELECT a, b FROM z' 2142 2143 Args: 2144 *expressions: the SQL code strings to parse. 2145 If an `Expression` instance is passed, it will be used as-is. 2146 append: if `True`, add to any existing expressions. 2147 Otherwise, this resets the expressions. 2148 dialect: the dialect used to parse the input expressions. 2149 copy: if `False`, modify this expression instance in-place. 2150 opts: other options to use to parse the input expressions. 2151 2152 Returns: 2153 Union: the modified expression. 2154 """ 2155 this = self.copy() if copy else self 2156 this.this.unnest().select(*expressions, append=append, dialect=dialect, copy=False, **opts) 2157 this.expression.unnest().select( 2158 *expressions, append=append, dialect=dialect, copy=False, **opts 2159 ) 2160 return this 2161 2162 @property 2163 def named_selects(self): 2164 return self.this.unnest().named_selects 2165 2166 @property 2167 def is_star(self) -> bool: 2168 return self.this.is_star or self.expression.is_star 2169 2170 @property 2171 def selects(self): 2172 return self.this.unnest().selects 2173 2174 @property 2175 def left(self): 2176 return self.this 2177 2178 @property 2179 def right(self): 2180 return self.expression
2102 def limit(self, expression, dialect=None, copy=True, **opts) -> Select: 2103 """ 2104 Set the LIMIT expression. 2105 2106 Example: 2107 >>> select("1").union(select("1")).limit(1).sql() 2108 'SELECT * FROM (SELECT 1 UNION SELECT 1) AS _l_0 LIMIT 1' 2109 2110 Args: 2111 expression (str | int | Expression): the SQL code string to parse. 2112 This can also be an integer. 2113 If a `Limit` instance is passed, this is used as-is. 2114 If another `Expression` instance is passed, it will be wrapped in a `Limit`. 2115 dialect (str): the dialect used to parse the input expression. 2116 copy (bool): if `False`, modify this expression instance in-place. 2117 opts (kwargs): other options to use to parse the input expressions. 2118 2119 Returns: 2120 Select: The limited subqueryable. 2121 """ 2122 return ( 2123 select("*") 2124 .from_(self.subquery(alias="_l_0", copy=copy)) 2125 .limit(expression, dialect=dialect, copy=False, **opts) 2126 )
Set the LIMIT expression.
Example:
>>> select("1").union(select("1")).limit(1).sql() 'SELECT * FROM (SELECT 1 UNION SELECT 1) AS _l_0 LIMIT 1'
Arguments:
- expression (str | int | Expression): the SQL code string to parse.
This can also be an integer.
If a
Limitinstance is passed, this is used as-is. If anotherExpressioninstance is passed, it will be wrapped in aLimit. - dialect (str): the dialect used to parse the input expression.
- copy (bool): if
False, modify this expression instance in-place. - opts (kwargs): other options to use to parse the input expressions.
Returns:
Select: The limited subqueryable.
2128 def select( 2129 self, 2130 *expressions: ExpOrStr, 2131 append: bool = True, 2132 dialect: DialectType = None, 2133 copy: bool = True, 2134 **opts, 2135 ) -> Union: 2136 """Append to or set the SELECT of the union recursively. 2137 2138 Example: 2139 >>> from sqlglot import parse_one 2140 >>> parse_one("select a from x union select a from y union select a from z").select("b").sql() 2141 'SELECT a, b FROM x UNION SELECT a, b FROM y UNION SELECT a, b FROM z' 2142 2143 Args: 2144 *expressions: the SQL code strings to parse. 2145 If an `Expression` instance is passed, it will be used as-is. 2146 append: if `True`, add to any existing expressions. 2147 Otherwise, this resets the expressions. 2148 dialect: the dialect used to parse the input expressions. 2149 copy: if `False`, modify this expression instance in-place. 2150 opts: other options to use to parse the input expressions. 2151 2152 Returns: 2153 Union: the modified expression. 2154 """ 2155 this = self.copy() if copy else self 2156 this.this.unnest().select(*expressions, append=append, dialect=dialect, copy=False, **opts) 2157 this.expression.unnest().select( 2158 *expressions, append=append, dialect=dialect, copy=False, **opts 2159 ) 2160 return this
Append to or set the SELECT of the union recursively.
Example:
>>> from sqlglot import parse_one >>> parse_one("select a from x union select a from y union select a from z").select("b").sql() 'SELECT a, b FROM x UNION SELECT a, b FROM y UNION SELECT a, b FROM z'
Arguments:
- *expressions: the SQL code strings to parse.
If an
Expressioninstance is passed, it will be used as-is. - append: if
True, add to any existing expressions. Otherwise, this resets the expressions. - dialect: the dialect used to parse the input expressions.
- copy: if
False, modify this expression instance in-place. - opts: other options to use to parse the input expressions.
Returns:
Union: the modified expression.
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
2191class Unnest(UDTF): 2192 arg_types = { 2193 "expressions": True, 2194 "ordinality": False, 2195 "alias": False, 2196 "offset": False, 2197 }
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
2200class Update(Expression): 2201 arg_types = { 2202 "with": False, 2203 "this": False, 2204 "expressions": True, 2205 "from": False, 2206 "where": False, 2207 "returning": False, 2208 }
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
2211class Values(UDTF): 2212 arg_types = { 2213 "expressions": True, 2214 "ordinality": False, 2215 "alias": False, 2216 }
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
2233class Select(Subqueryable): 2234 arg_types = { 2235 "with": False, 2236 "kind": False, 2237 "expressions": False, 2238 "hint": False, 2239 "distinct": False, 2240 "into": False, 2241 "from": False, 2242 **QUERY_MODIFIERS, 2243 } 2244 2245 def from_(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select: 2246 """ 2247 Set the FROM expression. 2248 2249 Example: 2250 >>> Select().from_("tbl").select("x").sql() 2251 'SELECT x FROM tbl' 2252 2253 Args: 2254 *expressions (str | Expression): the SQL code strings to parse. 2255 If a `From` instance is passed, this is used as-is. 2256 If another `Expression` instance is passed, it will be wrapped in a `From`. 2257 append (bool): if `True`, add to any existing expressions. 2258 Otherwise, this flattens all the `From` expression into a single expression. 2259 dialect (str): the dialect used to parse the input expression. 2260 copy (bool): if `False`, modify this expression instance in-place. 2261 opts (kwargs): other options to use to parse the input expressions. 2262 2263 Returns: 2264 Select: the modified expression. 2265 """ 2266 return _apply_child_list_builder( 2267 *expressions, 2268 instance=self, 2269 arg="from", 2270 append=append, 2271 copy=copy, 2272 prefix="FROM", 2273 into=From, 2274 dialect=dialect, 2275 **opts, 2276 ) 2277 2278 def group_by(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select: 2279 """ 2280 Set the GROUP BY expression. 2281 2282 Example: 2283 >>> Select().from_("tbl").select("x", "COUNT(1)").group_by("x").sql() 2284 'SELECT x, COUNT(1) FROM tbl GROUP BY x' 2285 2286 Args: 2287 *expressions (str | Expression): the SQL code strings to parse. 2288 If a `Group` instance is passed, this is used as-is. 2289 If another `Expression` instance is passed, it will be wrapped in a `Group`. 2290 If nothing is passed in then a group by is not applied to the expression 2291 append (bool): if `True`, add to any existing expressions. 2292 Otherwise, this flattens all the `Group` expression into a single expression. 2293 dialect (str): the dialect used to parse the input expression. 2294 copy (bool): if `False`, modify this expression instance in-place. 2295 opts (kwargs): other options to use to parse the input expressions. 2296 2297 Returns: 2298 Select: the modified expression. 2299 """ 2300 if not expressions: 2301 return self if not copy else self.copy() 2302 return _apply_child_list_builder( 2303 *expressions, 2304 instance=self, 2305 arg="group", 2306 append=append, 2307 copy=copy, 2308 prefix="GROUP BY", 2309 into=Group, 2310 dialect=dialect, 2311 **opts, 2312 ) 2313 2314 def order_by(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select: 2315 """ 2316 Set the ORDER BY expression. 2317 2318 Example: 2319 >>> Select().from_("tbl").select("x").order_by("x DESC").sql() 2320 'SELECT x FROM tbl ORDER BY x DESC' 2321 2322 Args: 2323 *expressions (str | Expression): the SQL code strings to parse. 2324 If a `Group` instance is passed, this is used as-is. 2325 If another `Expression` instance is passed, it will be wrapped in a `Order`. 2326 append (bool): if `True`, add to any existing expressions. 2327 Otherwise, this flattens all the `Order` expression into a single expression. 2328 dialect (str): the dialect used to parse the input expression. 2329 copy (bool): if `False`, modify this expression instance in-place. 2330 opts (kwargs): other options to use to parse the input expressions. 2331 2332 Returns: 2333 Select: the modified expression. 2334 """ 2335 return _apply_child_list_builder( 2336 *expressions, 2337 instance=self, 2338 arg="order", 2339 append=append, 2340 copy=copy, 2341 prefix="ORDER BY", 2342 into=Order, 2343 dialect=dialect, 2344 **opts, 2345 ) 2346 2347 def sort_by(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select: 2348 """ 2349 Set the SORT BY expression. 2350 2351 Example: 2352 >>> Select().from_("tbl").select("x").sort_by("x DESC").sql() 2353 'SELECT x FROM tbl SORT BY x DESC' 2354 2355 Args: 2356 *expressions (str | Expression): the SQL code strings to parse. 2357 If a `Group` instance is passed, this is used as-is. 2358 If another `Expression` instance is passed, it will be wrapped in a `SORT`. 2359 append (bool): if `True`, add to any existing expressions. 2360 Otherwise, this flattens all the `Order` expression into a single expression. 2361 dialect (str): the dialect used to parse the input expression. 2362 copy (bool): if `False`, modify this expression instance in-place. 2363 opts (kwargs): other options to use to parse the input expressions. 2364 2365 Returns: 2366 Select: the modified expression. 2367 """ 2368 return _apply_child_list_builder( 2369 *expressions, 2370 instance=self, 2371 arg="sort", 2372 append=append, 2373 copy=copy, 2374 prefix="SORT BY", 2375 into=Sort, 2376 dialect=dialect, 2377 **opts, 2378 ) 2379 2380 def cluster_by(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select: 2381 """ 2382 Set the CLUSTER BY expression. 2383 2384 Example: 2385 >>> Select().from_("tbl").select("x").cluster_by("x DESC").sql() 2386 'SELECT x FROM tbl CLUSTER BY x DESC' 2387 2388 Args: 2389 *expressions (str | Expression): the SQL code strings to parse. 2390 If a `Group` instance is passed, this is used as-is. 2391 If another `Expression` instance is passed, it will be wrapped in a `Cluster`. 2392 append (bool): if `True`, add to any existing expressions. 2393 Otherwise, this flattens all the `Order` expression into a single expression. 2394 dialect (str): the dialect used to parse the input expression. 2395 copy (bool): if `False`, modify this expression instance in-place. 2396 opts (kwargs): other options to use to parse the input expressions. 2397 2398 Returns: 2399 Select: the modified expression. 2400 """ 2401 return _apply_child_list_builder( 2402 *expressions, 2403 instance=self, 2404 arg="cluster", 2405 append=append, 2406 copy=copy, 2407 prefix="CLUSTER BY", 2408 into=Cluster, 2409 dialect=dialect, 2410 **opts, 2411 ) 2412 2413 def limit(self, expression, dialect=None, copy=True, **opts) -> Select: 2414 """ 2415 Set the LIMIT expression. 2416 2417 Example: 2418 >>> Select().from_("tbl").select("x").limit(10).sql() 2419 'SELECT x FROM tbl LIMIT 10' 2420 2421 Args: 2422 expression (str | int | Expression): the SQL code string to parse. 2423 This can also be an integer. 2424 If a `Limit` instance is passed, this is used as-is. 2425 If another `Expression` instance is passed, it will be wrapped in a `Limit`. 2426 dialect (str): the dialect used to parse the input expression. 2427 copy (bool): if `False`, modify this expression instance in-place. 2428 opts (kwargs): other options to use to parse the input expressions. 2429 2430 Returns: 2431 Select: the modified expression. 2432 """ 2433 return _apply_builder( 2434 expression=expression, 2435 instance=self, 2436 arg="limit", 2437 into=Limit, 2438 prefix="LIMIT", 2439 dialect=dialect, 2440 copy=copy, 2441 **opts, 2442 ) 2443 2444 def offset(self, expression, dialect=None, copy=True, **opts) -> Select: 2445 """ 2446 Set the OFFSET expression. 2447 2448 Example: 2449 >>> Select().from_("tbl").select("x").offset(10).sql() 2450 'SELECT x FROM tbl OFFSET 10' 2451 2452 Args: 2453 expression (str | int | Expression): the SQL code string to parse. 2454 This can also be an integer. 2455 If a `Offset` instance is passed, this is used as-is. 2456 If another `Expression` instance is passed, it will be wrapped in a `Offset`. 2457 dialect (str): the dialect used to parse the input expression. 2458 copy (bool): if `False`, modify this expression instance in-place. 2459 opts (kwargs): other options to use to parse the input expressions. 2460 2461 Returns: 2462 Select: the modified expression. 2463 """ 2464 return _apply_builder( 2465 expression=expression, 2466 instance=self, 2467 arg="offset", 2468 into=Offset, 2469 prefix="OFFSET", 2470 dialect=dialect, 2471 copy=copy, 2472 **opts, 2473 ) 2474 2475 def select( 2476 self, 2477 *expressions: ExpOrStr, 2478 append: bool = True, 2479 dialect: DialectType = None, 2480 copy: bool = True, 2481 **opts, 2482 ) -> Select: 2483 """ 2484 Append to or set the SELECT expressions. 2485 2486 Example: 2487 >>> Select().select("x", "y").sql() 2488 'SELECT x, y' 2489 2490 Args: 2491 *expressions: the SQL code strings to parse. 2492 If an `Expression` instance is passed, it will be used as-is. 2493 append: if `True`, add to any existing expressions. 2494 Otherwise, this resets the expressions. 2495 dialect: the dialect used to parse the input expressions. 2496 copy: if `False`, modify this expression instance in-place. 2497 opts: other options to use to parse the input expressions. 2498 2499 Returns: 2500 Select: the modified expression. 2501 """ 2502 return _apply_list_builder( 2503 *expressions, 2504 instance=self, 2505 arg="expressions", 2506 append=append, 2507 dialect=dialect, 2508 copy=copy, 2509 **opts, 2510 ) 2511 2512 def lateral(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select: 2513 """ 2514 Append to or set the LATERAL expressions. 2515 2516 Example: 2517 >>> Select().select("x").lateral("OUTER explode(y) tbl2 AS z").from_("tbl").sql() 2518 'SELECT x FROM tbl LATERAL VIEW OUTER EXPLODE(y) tbl2 AS z' 2519 2520 Args: 2521 *expressions (str | Expression): the SQL code strings to parse. 2522 If an `Expression` instance is passed, it will be used as-is. 2523 append (bool): if `True`, add to any existing expressions. 2524 Otherwise, this resets the expressions. 2525 dialect (str): the dialect used to parse the input expressions. 2526 copy (bool): if `False`, modify this expression instance in-place. 2527 opts (kwargs): other options to use to parse the input expressions. 2528 2529 Returns: 2530 Select: the modified expression. 2531 """ 2532 return _apply_list_builder( 2533 *expressions, 2534 instance=self, 2535 arg="laterals", 2536 append=append, 2537 into=Lateral, 2538 prefix="LATERAL VIEW", 2539 dialect=dialect, 2540 copy=copy, 2541 **opts, 2542 ) 2543 2544 def join( 2545 self, 2546 expression, 2547 on=None, 2548 using=None, 2549 append=True, 2550 join_type=None, 2551 join_alias=None, 2552 dialect=None, 2553 copy=True, 2554 **opts, 2555 ) -> Select: 2556 """ 2557 Append to or set the JOIN expressions. 2558 2559 Example: 2560 >>> Select().select("*").from_("tbl").join("tbl2", on="tbl1.y = tbl2.y").sql() 2561 'SELECT * FROM tbl JOIN tbl2 ON tbl1.y = tbl2.y' 2562 2563 >>> Select().select("1").from_("a").join("b", using=["x", "y", "z"]).sql() 2564 'SELECT 1 FROM a JOIN b USING (x, y, z)' 2565 2566 Use `join_type` to change the type of join: 2567 2568 >>> Select().select("*").from_("tbl").join("tbl2", on="tbl1.y = tbl2.y", join_type="left outer").sql() 2569 'SELECT * FROM tbl LEFT OUTER JOIN tbl2 ON tbl1.y = tbl2.y' 2570 2571 Args: 2572 expression (str | Expression): the SQL code string to parse. 2573 If an `Expression` instance is passed, it will be used as-is. 2574 on (str | Expression): optionally specify the join "on" criteria as a SQL string. 2575 If an `Expression` instance is passed, it will be used as-is. 2576 using (str | Expression): optionally specify the join "using" criteria as a SQL string. 2577 If an `Expression` instance is passed, it will be used as-is. 2578 append (bool): if `True`, add to any existing expressions. 2579 Otherwise, this resets the expressions. 2580 join_type (str): If set, alter the parsed join type 2581 dialect (str): the dialect used to parse the input expressions. 2582 copy (bool): if `False`, modify this expression instance in-place. 2583 opts (kwargs): other options to use to parse the input expressions. 2584 2585 Returns: 2586 Select: the modified expression. 2587 """ 2588 parse_args = {"dialect": dialect, **opts} 2589 2590 try: 2591 expression = maybe_parse(expression, into=Join, prefix="JOIN", **parse_args) 2592 except ParseError: 2593 expression = maybe_parse(expression, into=(Join, Expression), **parse_args) 2594 2595 join = expression if isinstance(expression, Join) else Join(this=expression) 2596 2597 if isinstance(join.this, Select): 2598 join.this.replace(join.this.subquery()) 2599 2600 if join_type: 2601 natural: t.Optional[Token] 2602 side: t.Optional[Token] 2603 kind: t.Optional[Token] 2604 2605 natural, side, kind = maybe_parse(join_type, into="JOIN_TYPE", **parse_args) # type: ignore 2606 2607 if natural: 2608 join.set("natural", True) 2609 if side: 2610 join.set("side", side.text) 2611 if kind: 2612 join.set("kind", kind.text) 2613 2614 if on: 2615 on = and_(*ensure_collection(on), dialect=dialect, **opts) 2616 join.set("on", on) 2617 2618 if using: 2619 join = _apply_list_builder( 2620 *ensure_collection(using), 2621 instance=join, 2622 arg="using", 2623 append=append, 2624 copy=copy, 2625 **opts, 2626 ) 2627 2628 if join_alias: 2629 join.set("this", alias_(join.this, join_alias, table=True)) 2630 return _apply_list_builder( 2631 join, 2632 instance=self, 2633 arg="joins", 2634 append=append, 2635 copy=copy, 2636 **opts, 2637 ) 2638 2639 def where(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select: 2640 """ 2641 Append to or set the WHERE expressions. 2642 2643 Example: 2644 >>> Select().select("x").from_("tbl").where("x = 'a' OR x < 'b'").sql() 2645 "SELECT x FROM tbl WHERE x = 'a' OR x < 'b'" 2646 2647 Args: 2648 *expressions (str | Expression): the SQL code strings to parse. 2649 If an `Expression` instance is passed, it will be used as-is. 2650 Multiple expressions are combined with an AND operator. 2651 append (bool): if `True`, AND the new expressions to any existing expression. 2652 Otherwise, this resets the expression. 2653 dialect (str): the dialect used to parse the input expressions. 2654 copy (bool): if `False`, modify this expression instance in-place. 2655 opts (kwargs): other options to use to parse the input expressions. 2656 2657 Returns: 2658 Select: the modified expression. 2659 """ 2660 return _apply_conjunction_builder( 2661 *expressions, 2662 instance=self, 2663 arg="where", 2664 append=append, 2665 into=Where, 2666 dialect=dialect, 2667 copy=copy, 2668 **opts, 2669 ) 2670 2671 def having(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select: 2672 """ 2673 Append to or set the HAVING expressions. 2674 2675 Example: 2676 >>> Select().select("x", "COUNT(y)").from_("tbl").group_by("x").having("COUNT(y) > 3").sql() 2677 'SELECT x, COUNT(y) FROM tbl GROUP BY x HAVING COUNT(y) > 3' 2678 2679 Args: 2680 *expressions (str | Expression): the SQL code strings to parse. 2681 If an `Expression` instance is passed, it will be used as-is. 2682 Multiple expressions are combined with an AND operator. 2683 append (bool): if `True`, AND the new expressions to any existing expression. 2684 Otherwise, this resets the expression. 2685 dialect (str): the dialect used to parse the input expressions. 2686 copy (bool): if `False`, modify this expression instance in-place. 2687 opts (kwargs): other options to use to parse the input expressions. 2688 2689 Returns: 2690 Select: the modified expression. 2691 """ 2692 return _apply_conjunction_builder( 2693 *expressions, 2694 instance=self, 2695 arg="having", 2696 append=append, 2697 into=Having, 2698 dialect=dialect, 2699 copy=copy, 2700 **opts, 2701 ) 2702 2703 def window(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select: 2704 return _apply_list_builder( 2705 *expressions, 2706 instance=self, 2707 arg="windows", 2708 append=append, 2709 into=Window, 2710 dialect=dialect, 2711 copy=copy, 2712 **opts, 2713 ) 2714 2715 def qualify(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select: 2716 return _apply_conjunction_builder( 2717 *expressions, 2718 instance=self, 2719 arg="qualify", 2720 append=append, 2721 into=Qualify, 2722 dialect=dialect, 2723 copy=copy, 2724 **opts, 2725 ) 2726 2727 def distinct(self, distinct=True, copy=True) -> Select: 2728 """ 2729 Set the OFFSET expression. 2730 2731 Example: 2732 >>> Select().from_("tbl").select("x").distinct().sql() 2733 'SELECT DISTINCT x FROM tbl' 2734 2735 Args: 2736 distinct (bool): whether the Select should be distinct 2737 copy (bool): if `False`, modify this expression instance in-place. 2738 2739 Returns: 2740 Select: the modified expression. 2741 """ 2742 instance = _maybe_copy(self, copy) 2743 instance.set("distinct", Distinct() if distinct else None) 2744 return instance 2745 2746 def ctas(self, table, properties=None, dialect=None, copy=True, **opts) -> Create: 2747 """ 2748 Convert this expression to a CREATE TABLE AS statement. 2749 2750 Example: 2751 >>> Select().select("*").from_("tbl").ctas("x").sql() 2752 'CREATE TABLE x AS SELECT * FROM tbl' 2753 2754 Args: 2755 table (str | Expression): the SQL code string to parse as the table name. 2756 If another `Expression` instance is passed, it will be used as-is. 2757 properties (dict): an optional mapping of table properties 2758 dialect (str): the dialect used to parse the input table. 2759 copy (bool): if `False`, modify this expression instance in-place. 2760 opts (kwargs): other options to use to parse the input table. 2761 2762 Returns: 2763 Create: the CREATE TABLE AS expression 2764 """ 2765 instance = _maybe_copy(self, copy) 2766 table_expression = maybe_parse( 2767 table, 2768 into=Table, 2769 dialect=dialect, 2770 **opts, 2771 ) 2772 properties_expression = None 2773 if properties: 2774 properties_expression = Properties.from_dict(properties) 2775 2776 return Create( 2777 this=table_expression, 2778 kind="table", 2779 expression=instance, 2780 properties=properties_expression, 2781 ) 2782 2783 def lock(self, update: bool = True, copy: bool = True) -> Select: 2784 """ 2785 Set the locking read mode for this expression. 2786 2787 Examples: 2788 >>> Select().select("x").from_("tbl").where("x = 'a'").lock().sql("mysql") 2789 "SELECT x FROM tbl WHERE x = 'a' FOR UPDATE" 2790 2791 >>> Select().select("x").from_("tbl").where("x = 'a'").lock(update=False).sql("mysql") 2792 "SELECT x FROM tbl WHERE x = 'a' FOR SHARE" 2793 2794 Args: 2795 update: if `True`, the locking type will be `FOR UPDATE`, else it will be `FOR SHARE`. 2796 copy: if `False`, modify this expression instance in-place. 2797 2798 Returns: 2799 The modified expression. 2800 """ 2801 2802 inst = _maybe_copy(self, copy) 2803 inst.set("lock", Lock(update=update)) 2804 2805 return inst 2806 2807 @property 2808 def named_selects(self) -> t.List[str]: 2809 return [e.output_name for e in self.expressions if e.alias_or_name] 2810 2811 @property 2812 def is_star(self) -> bool: 2813 return any(expression.is_star for expression in self.expressions) 2814 2815 @property 2816 def selects(self) -> t.List[Expression]: 2817 return self.expressions
2245 def from_(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select: 2246 """ 2247 Set the FROM expression. 2248 2249 Example: 2250 >>> Select().from_("tbl").select("x").sql() 2251 'SELECT x FROM tbl' 2252 2253 Args: 2254 *expressions (str | Expression): the SQL code strings to parse. 2255 If a `From` instance is passed, this is used as-is. 2256 If another `Expression` instance is passed, it will be wrapped in a `From`. 2257 append (bool): if `True`, add to any existing expressions. 2258 Otherwise, this flattens all the `From` expression into a single expression. 2259 dialect (str): the dialect used to parse the input expression. 2260 copy (bool): if `False`, modify this expression instance in-place. 2261 opts (kwargs): other options to use to parse the input expressions. 2262 2263 Returns: 2264 Select: the modified expression. 2265 """ 2266 return _apply_child_list_builder( 2267 *expressions, 2268 instance=self, 2269 arg="from", 2270 append=append, 2271 copy=copy, 2272 prefix="FROM", 2273 into=From, 2274 dialect=dialect, 2275 **opts, 2276 )
Set the FROM expression.
Example:
>>> Select().from_("tbl").select("x").sql() 'SELECT x FROM tbl'
Arguments:
- *expressions (str | Expression): the SQL code strings to parse.
If a
Frominstance is passed, this is used as-is. If anotherExpressioninstance is passed, it will be wrapped in aFrom. - append (bool): if
True, add to any existing expressions. Otherwise, this flattens all theFromexpression into a single expression. - dialect (str): the dialect used to parse the input expression.
- copy (bool): if
False, modify this expression instance in-place. - opts (kwargs): other options to use to parse the input expressions.
Returns:
Select: the modified expression.
2278 def group_by(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select: 2279 """ 2280 Set the GROUP BY expression. 2281 2282 Example: 2283 >>> Select().from_("tbl").select("x", "COUNT(1)").group_by("x").sql() 2284 'SELECT x, COUNT(1) FROM tbl GROUP BY x' 2285 2286 Args: 2287 *expressions (str | Expression): the SQL code strings to parse. 2288 If a `Group` instance is passed, this is used as-is. 2289 If another `Expression` instance is passed, it will be wrapped in a `Group`. 2290 If nothing is passed in then a group by is not applied to the expression 2291 append (bool): if `True`, add to any existing expressions. 2292 Otherwise, this flattens all the `Group` expression into a single expression. 2293 dialect (str): the dialect used to parse the input expression. 2294 copy (bool): if `False`, modify this expression instance in-place. 2295 opts (kwargs): other options to use to parse the input expressions. 2296 2297 Returns: 2298 Select: the modified expression. 2299 """ 2300 if not expressions: 2301 return self if not copy else self.copy() 2302 return _apply_child_list_builder( 2303 *expressions, 2304 instance=self, 2305 arg="group", 2306 append=append, 2307 copy=copy, 2308 prefix="GROUP BY", 2309 into=Group, 2310 dialect=dialect, 2311 **opts, 2312 )
Set the GROUP BY expression.
Example:
>>> Select().from_("tbl").select("x", "COUNT(1)").group_by("x").sql() 'SELECT x, COUNT(1) FROM tbl GROUP BY x'
Arguments:
- *expressions (str | Expression): the SQL code strings to parse.
If a
Groupinstance is passed, this is used as-is. If anotherExpressioninstance is passed, it will be wrapped in aGroup. If nothing is passed in then a group by is not applied to the expression - append (bool): if
True, add to any existing expressions. Otherwise, this flattens all theGroupexpression into a single expression. - dialect (str): the dialect used to parse the input expression.
- copy (bool): if
False, modify this expression instance in-place. - opts (kwargs): other options to use to parse the input expressions.
Returns:
Select: the modified expression.
2314 def order_by(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select: 2315 """ 2316 Set the ORDER BY expression. 2317 2318 Example: 2319 >>> Select().from_("tbl").select("x").order_by("x DESC").sql() 2320 'SELECT x FROM tbl ORDER BY x DESC' 2321 2322 Args: 2323 *expressions (str | Expression): the SQL code strings to parse. 2324 If a `Group` instance is passed, this is used as-is. 2325 If another `Expression` instance is passed, it will be wrapped in a `Order`. 2326 append (bool): if `True`, add to any existing expressions. 2327 Otherwise, this flattens all the `Order` expression into a single expression. 2328 dialect (str): the dialect used to parse the input expression. 2329 copy (bool): if `False`, modify this expression instance in-place. 2330 opts (kwargs): other options to use to parse the input expressions. 2331 2332 Returns: 2333 Select: the modified expression. 2334 """ 2335 return _apply_child_list_builder( 2336 *expressions, 2337 instance=self, 2338 arg="order", 2339 append=append, 2340 copy=copy, 2341 prefix="ORDER BY", 2342 into=Order, 2343 dialect=dialect, 2344 **opts, 2345 )
Set the ORDER BY expression.
Example:
>>> Select().from_("tbl").select("x").order_by("x DESC").sql() 'SELECT x FROM tbl ORDER BY x DESC'
Arguments:
- *expressions (str | Expression): the SQL code strings to parse.
If a
Groupinstance is passed, this is used as-is. If anotherExpressioninstance is passed, it will be wrapped in aOrder. - append (bool): if
True, add to any existing expressions. Otherwise, this flattens all theOrderexpression into a single expression. - dialect (str): the dialect used to parse the input expression.
- copy (bool): if
False, modify this expression instance in-place. - opts (kwargs): other options to use to parse the input expressions.
Returns:
Select: the modified expression.
2347 def sort_by(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select: 2348 """ 2349 Set the SORT BY expression. 2350 2351 Example: 2352 >>> Select().from_("tbl").select("x").sort_by("x DESC").sql() 2353 'SELECT x FROM tbl SORT BY x DESC' 2354 2355 Args: 2356 *expressions (str | Expression): the SQL code strings to parse. 2357 If a `Group` instance is passed, this is used as-is. 2358 If another `Expression` instance is passed, it will be wrapped in a `SORT`. 2359 append (bool): if `True`, add to any existing expressions. 2360 Otherwise, this flattens all the `Order` expression into a single expression. 2361 dialect (str): the dialect used to parse the input expression. 2362 copy (bool): if `False`, modify this expression instance in-place. 2363 opts (kwargs): other options to use to parse the input expressions. 2364 2365 Returns: 2366 Select: the modified expression. 2367 """ 2368 return _apply_child_list_builder( 2369 *expressions, 2370 instance=self, 2371 arg="sort", 2372 append=append, 2373 copy=copy, 2374 prefix="SORT BY", 2375 into=Sort, 2376 dialect=dialect, 2377 **opts, 2378 )
Set the SORT BY expression.
Example:
>>> Select().from_("tbl").select("x").sort_by("x DESC").sql() 'SELECT x FROM tbl SORT BY x DESC'
Arguments:
- *expressions (str | Expression): the SQL code strings to parse.
If a
Groupinstance is passed, this is used as-is. If anotherExpressioninstance is passed, it will be wrapped in aSORT. - append (bool): if
True, add to any existing expressions. Otherwise, this flattens all theOrderexpression into a single expression. - dialect (str): the dialect used to parse the input expression.
- copy (bool): if
False, modify this expression instance in-place. - opts (kwargs): other options to use to parse the input expressions.
Returns:
Select: the modified expression.
2380 def cluster_by(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select: 2381 """ 2382 Set the CLUSTER BY expression. 2383 2384 Example: 2385 >>> Select().from_("tbl").select("x").cluster_by("x DESC").sql() 2386 'SELECT x FROM tbl CLUSTER BY x DESC' 2387 2388 Args: 2389 *expressions (str | Expression): the SQL code strings to parse. 2390 If a `Group` instance is passed, this is used as-is. 2391 If another `Expression` instance is passed, it will be wrapped in a `Cluster`. 2392 append (bool): if `True`, add to any existing expressions. 2393 Otherwise, this flattens all the `Order` expression into a single expression. 2394 dialect (str): the dialect used to parse the input expression. 2395 copy (bool): if `False`, modify this expression instance in-place. 2396 opts (kwargs): other options to use to parse the input expressions. 2397 2398 Returns: 2399 Select: the modified expression. 2400 """ 2401 return _apply_child_list_builder( 2402 *expressions, 2403 instance=self, 2404 arg="cluster", 2405 append=append, 2406 copy=copy, 2407 prefix="CLUSTER BY", 2408 into=Cluster, 2409 dialect=dialect, 2410 **opts, 2411 )
Set the CLUSTER BY expression.
Example:
>>> Select().from_("tbl").select("x").cluster_by("x DESC").sql() 'SELECT x FROM tbl CLUSTER BY x DESC'
Arguments:
- *expressions (str | Expression): the SQL code strings to parse.
If a
Groupinstance is passed, this is used as-is. If anotherExpressioninstance is passed, it will be wrapped in aCluster. - append (bool): if
True, add to any existing expressions. Otherwise, this flattens all theOrderexpression into a single expression. - dialect (str): the dialect used to parse the input expression.
- copy (bool): if
False, modify this expression instance in-place. - opts (kwargs): other options to use to parse the input expressions.
Returns:
Select: the modified expression.
2413 def limit(self, expression, dialect=None, copy=True, **opts) -> Select: 2414 """ 2415 Set the LIMIT expression. 2416 2417 Example: 2418 >>> Select().from_("tbl").select("x").limit(10).sql() 2419 'SELECT x FROM tbl LIMIT 10' 2420 2421 Args: 2422 expression (str | int | Expression): the SQL code string to parse. 2423 This can also be an integer. 2424 If a `Limit` instance is passed, this is used as-is. 2425 If another `Expression` instance is passed, it will be wrapped in a `Limit`. 2426 dialect (str): the dialect used to parse the input expression. 2427 copy (bool): if `False`, modify this expression instance in-place. 2428 opts (kwargs): other options to use to parse the input expressions. 2429 2430 Returns: 2431 Select: the modified expression. 2432 """ 2433 return _apply_builder( 2434 expression=expression, 2435 instance=self, 2436 arg="limit", 2437 into=Limit, 2438 prefix="LIMIT", 2439 dialect=dialect, 2440 copy=copy, 2441 **opts, 2442 )
Set the LIMIT expression.
Example:
>>> Select().from_("tbl").select("x").limit(10).sql() 'SELECT x FROM tbl LIMIT 10'
Arguments:
- expression (str | int | Expression): the SQL code string to parse.
This can also be an integer.
If a
Limitinstance is passed, this is used as-is. If anotherExpressioninstance is passed, it will be wrapped in aLimit. - dialect (str): the dialect used to parse the input expression.
- copy (bool): if
False, modify this expression instance in-place. - opts (kwargs): other options to use to parse the input expressions.
Returns:
Select: the modified expression.
2444 def offset(self, expression, dialect=None, copy=True, **opts) -> Select: 2445 """ 2446 Set the OFFSET expression. 2447 2448 Example: 2449 >>> Select().from_("tbl").select("x").offset(10).sql() 2450 'SELECT x FROM tbl OFFSET 10' 2451 2452 Args: 2453 expression (str | int | Expression): the SQL code string to parse. 2454 This can also be an integer. 2455 If a `Offset` instance is passed, this is used as-is. 2456 If another `Expression` instance is passed, it will be wrapped in a `Offset`. 2457 dialect (str): the dialect used to parse the input expression. 2458 copy (bool): if `False`, modify this expression instance in-place. 2459 opts (kwargs): other options to use to parse the input expressions. 2460 2461 Returns: 2462 Select: the modified expression. 2463 """ 2464 return _apply_builder( 2465 expression=expression, 2466 instance=self, 2467 arg="offset", 2468 into=Offset, 2469 prefix="OFFSET", 2470 dialect=dialect, 2471 copy=copy, 2472 **opts, 2473 )
Set the OFFSET expression.
Example:
>>> Select().from_("tbl").select("x").offset(10).sql() 'SELECT x FROM tbl OFFSET 10'
Arguments:
- expression (str | int | Expression): the SQL code string to parse.
This can also be an integer.
If a
Offsetinstance is passed, this is used as-is. If anotherExpressioninstance is passed, it will be wrapped in aOffset. - dialect (str): the dialect used to parse the input expression.
- copy (bool): if
False, modify this expression instance in-place. - opts (kwargs): other options to use to parse the input expressions.
Returns:
Select: the modified expression.
2475 def select( 2476 self, 2477 *expressions: ExpOrStr, 2478 append: bool = True, 2479 dialect: DialectType = None, 2480 copy: bool = True, 2481 **opts, 2482 ) -> Select: 2483 """ 2484 Append to or set the SELECT expressions. 2485 2486 Example: 2487 >>> Select().select("x", "y").sql() 2488 'SELECT x, y' 2489 2490 Args: 2491 *expressions: the SQL code strings to parse. 2492 If an `Expression` instance is passed, it will be used as-is. 2493 append: if `True`, add to any existing expressions. 2494 Otherwise, this resets the expressions. 2495 dialect: the dialect used to parse the input expressions. 2496 copy: if `False`, modify this expression instance in-place. 2497 opts: other options to use to parse the input expressions. 2498 2499 Returns: 2500 Select: the modified expression. 2501 """ 2502 return _apply_list_builder( 2503 *expressions, 2504 instance=self, 2505 arg="expressions", 2506 append=append, 2507 dialect=dialect, 2508 copy=copy, 2509 **opts, 2510 )
Append to or set the SELECT expressions.
Example:
>>> Select().select("x", "y").sql() 'SELECT x, y'
Arguments:
- *expressions: the SQL code strings to parse.
If an
Expressioninstance is passed, it will be used as-is. - append: if
True, add to any existing expressions. Otherwise, this resets the expressions. - dialect: the dialect used to parse the input expressions.
- copy: if
False, modify this expression instance in-place. - opts: other options to use to parse the input expressions.
Returns:
Select: the modified expression.
2512 def lateral(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select: 2513 """ 2514 Append to or set the LATERAL expressions. 2515 2516 Example: 2517 >>> Select().select("x").lateral("OUTER explode(y) tbl2 AS z").from_("tbl").sql() 2518 'SELECT x FROM tbl LATERAL VIEW OUTER EXPLODE(y) tbl2 AS z' 2519 2520 Args: 2521 *expressions (str | Expression): the SQL code strings to parse. 2522 If an `Expression` instance is passed, it will be used as-is. 2523 append (bool): if `True`, add to any existing expressions. 2524 Otherwise, this resets the expressions. 2525 dialect (str): the dialect used to parse the input expressions. 2526 copy (bool): if `False`, modify this expression instance in-place. 2527 opts (kwargs): other options to use to parse the input expressions. 2528 2529 Returns: 2530 Select: the modified expression. 2531 """ 2532 return _apply_list_builder( 2533 *expressions, 2534 instance=self, 2535 arg="laterals", 2536 append=append, 2537 into=Lateral, 2538 prefix="LATERAL VIEW", 2539 dialect=dialect, 2540 copy=copy, 2541 **opts, 2542 )
Append to or set the LATERAL expressions.
Example:
>>> Select().select("x").lateral("OUTER explode(y) tbl2 AS z").from_("tbl").sql() 'SELECT x FROM tbl LATERAL VIEW OUTER EXPLODE(y) tbl2 AS z'
Arguments:
- *expressions (str | Expression): the SQL code strings to parse.
If an
Expressioninstance is passed, it will be used as-is. - append (bool): if
True, add to any existing expressions. Otherwise, this resets the expressions. - dialect (str): the dialect used to parse the input expressions.
- copy (bool): if
False, modify this expression instance in-place. - opts (kwargs): other options to use to parse the input expressions.
Returns:
Select: the modified expression.
2544 def join( 2545 self, 2546 expression, 2547 on=None, 2548 using=None, 2549 append=True, 2550 join_type=None, 2551 join_alias=None, 2552 dialect=None, 2553 copy=True, 2554 **opts, 2555 ) -> Select: 2556 """ 2557 Append to or set the JOIN expressions. 2558 2559 Example: 2560 >>> Select().select("*").from_("tbl").join("tbl2", on="tbl1.y = tbl2.y").sql() 2561 'SELECT * FROM tbl JOIN tbl2 ON tbl1.y = tbl2.y' 2562 2563 >>> Select().select("1").from_("a").join("b", using=["x", "y", "z"]).sql() 2564 'SELECT 1 FROM a JOIN b USING (x, y, z)' 2565 2566 Use `join_type` to change the type of join: 2567 2568 >>> Select().select("*").from_("tbl").join("tbl2", on="tbl1.y = tbl2.y", join_type="left outer").sql() 2569 'SELECT * FROM tbl LEFT OUTER JOIN tbl2 ON tbl1.y = tbl2.y' 2570 2571 Args: 2572 expression (str | Expression): the SQL code string to parse. 2573 If an `Expression` instance is passed, it will be used as-is. 2574 on (str | Expression): optionally specify the join "on" criteria as a SQL string. 2575 If an `Expression` instance is passed, it will be used as-is. 2576 using (str | Expression): optionally specify the join "using" criteria as a SQL string. 2577 If an `Expression` instance is passed, it will be used as-is. 2578 append (bool): if `True`, add to any existing expressions. 2579 Otherwise, this resets the expressions. 2580 join_type (str): If set, alter the parsed join type 2581 dialect (str): the dialect used to parse the input expressions. 2582 copy (bool): if `False`, modify this expression instance in-place. 2583 opts (kwargs): other options to use to parse the input expressions. 2584 2585 Returns: 2586 Select: the modified expression. 2587 """ 2588 parse_args = {"dialect": dialect, **opts} 2589 2590 try: 2591 expression = maybe_parse(expression, into=Join, prefix="JOIN", **parse_args) 2592 except ParseError: 2593 expression = maybe_parse(expression, into=(Join, Expression), **parse_args) 2594 2595 join = expression if isinstance(expression, Join) else Join(this=expression) 2596 2597 if isinstance(join.this, Select): 2598 join.this.replace(join.this.subquery()) 2599 2600 if join_type: 2601 natural: t.Optional[Token] 2602 side: t.Optional[Token] 2603 kind: t.Optional[Token] 2604 2605 natural, side, kind = maybe_parse(join_type, into="JOIN_TYPE", **parse_args) # type: ignore 2606 2607 if natural: 2608 join.set("natural", True) 2609 if side: 2610 join.set("side", side.text) 2611 if kind: 2612 join.set("kind", kind.text) 2613 2614 if on: 2615 on = and_(*ensure_collection(on), dialect=dialect, **opts) 2616 join.set("on", on) 2617 2618 if using: 2619 join = _apply_list_builder( 2620 *ensure_collection(using), 2621 instance=join, 2622 arg="using", 2623 append=append, 2624 copy=copy, 2625 **opts, 2626 ) 2627 2628 if join_alias: 2629 join.set("this", alias_(join.this, join_alias, table=True)) 2630 return _apply_list_builder( 2631 join, 2632 instance=self, 2633 arg="joins", 2634 append=append, 2635 copy=copy, 2636 **opts, 2637 )
Append to or set the JOIN expressions.
Example:
>>> Select().select("*").from_("tbl").join("tbl2", on="tbl1.y = tbl2.y").sql() 'SELECT * FROM tbl JOIN tbl2 ON tbl1.y = tbl2.y'>>> Select().select("1").from_("a").join("b", using=["x", "y", "z"]).sql() 'SELECT 1 FROM a JOIN b USING (x, y, z)'Use
join_typeto change the type of join:>>> Select().select("*").from_("tbl").join("tbl2", on="tbl1.y = tbl2.y", join_type="left outer").sql() 'SELECT * FROM tbl LEFT OUTER JOIN tbl2 ON tbl1.y = tbl2.y'
Arguments:
- expression (str | Expression): the SQL code string to parse.
If an
Expressioninstance is passed, it will be used as-is. - on (str | Expression): optionally specify the join "on" criteria as a SQL string.
If an
Expressioninstance is passed, it will be used as-is. - using (str | Expression): optionally specify the join "using" criteria as a SQL string.
If an
Expressioninstance is passed, it will be used as-is. - append (bool): if
True, add to any existing expressions. Otherwise, this resets the expressions. - join_type (str): If set, alter the parsed join type
- dialect (str): the dialect used to parse the input expressions.
- copy (bool): if
False, modify this expression instance in-place. - opts (kwargs): other options to use to parse the input expressions.
Returns:
Select: the modified expression.
2639 def where(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select: 2640 """ 2641 Append to or set the WHERE expressions. 2642 2643 Example: 2644 >>> Select().select("x").from_("tbl").where("x = 'a' OR x < 'b'").sql() 2645 "SELECT x FROM tbl WHERE x = 'a' OR x < 'b'" 2646 2647 Args: 2648 *expressions (str | Expression): the SQL code strings to parse. 2649 If an `Expression` instance is passed, it will be used as-is. 2650 Multiple expressions are combined with an AND operator. 2651 append (bool): if `True`, AND the new expressions to any existing expression. 2652 Otherwise, this resets the expression. 2653 dialect (str): the dialect used to parse the input expressions. 2654 copy (bool): if `False`, modify this expression instance in-place. 2655 opts (kwargs): other options to use to parse the input expressions. 2656 2657 Returns: 2658 Select: the modified expression. 2659 """ 2660 return _apply_conjunction_builder( 2661 *expressions, 2662 instance=self, 2663 arg="where", 2664 append=append, 2665 into=Where, 2666 dialect=dialect, 2667 copy=copy, 2668 **opts, 2669 )
Append to or set the WHERE expressions.
Example:
>>> Select().select("x").from_("tbl").where("x = 'a' OR x < 'b'").sql() "SELECT x FROM tbl WHERE x = 'a' OR x < 'b'"
Arguments:
- *expressions (str | Expression): the SQL code strings to parse.
If an
Expressioninstance is passed, it will be used as-is. Multiple expressions are combined with an AND operator. - append (bool): if
True, AND the new expressions to any existing expression. Otherwise, this resets the expression. - dialect (str): the dialect used to parse the input expressions.
- copy (bool): if
False, modify this expression instance in-place. - opts (kwargs): other options to use to parse the input expressions.
Returns:
Select: the modified expression.
2671 def having(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select: 2672 """ 2673 Append to or set the HAVING expressions. 2674 2675 Example: 2676 >>> Select().select("x", "COUNT(y)").from_("tbl").group_by("x").having("COUNT(y) > 3").sql() 2677 'SELECT x, COUNT(y) FROM tbl GROUP BY x HAVING COUNT(y) > 3' 2678 2679 Args: 2680 *expressions (str | Expression): the SQL code strings to parse. 2681 If an `Expression` instance is passed, it will be used as-is. 2682 Multiple expressions are combined with an AND operator. 2683 append (bool): if `True`, AND the new expressions to any existing expression. 2684 Otherwise, this resets the expression. 2685 dialect (str): the dialect used to parse the input expressions. 2686 copy (bool): if `False`, modify this expression instance in-place. 2687 opts (kwargs): other options to use to parse the input expressions. 2688 2689 Returns: 2690 Select: the modified expression. 2691 """ 2692 return _apply_conjunction_builder( 2693 *expressions, 2694 instance=self, 2695 arg="having", 2696 append=append, 2697 into=Having, 2698 dialect=dialect, 2699 copy=copy, 2700 **opts, 2701 )
Append to or set the HAVING expressions.
Example:
>>> Select().select("x", "COUNT(y)").from_("tbl").group_by("x").having("COUNT(y) > 3").sql() 'SELECT x, COUNT(y) FROM tbl GROUP BY x HAVING COUNT(y) > 3'
Arguments:
- *expressions (str | Expression): the SQL code strings to parse.
If an
Expressioninstance is passed, it will be used as-is. Multiple expressions are combined with an AND operator. - append (bool): if
True, AND the new expressions to any existing expression. Otherwise, this resets the expression. - dialect (str): the dialect used to parse the input expressions.
- copy (bool): if
False, modify this expression instance in-place. - opts (kwargs): other options to use to parse the input expressions.
Returns:
Select: the modified expression.
2727 def distinct(self, distinct=True, copy=True) -> Select: 2728 """ 2729 Set the OFFSET expression. 2730 2731 Example: 2732 >>> Select().from_("tbl").select("x").distinct().sql() 2733 'SELECT DISTINCT x FROM tbl' 2734 2735 Args: 2736 distinct (bool): whether the Select should be distinct 2737 copy (bool): if `False`, modify this expression instance in-place. 2738 2739 Returns: 2740 Select: the modified expression. 2741 """ 2742 instance = _maybe_copy(self, copy) 2743 instance.set("distinct", Distinct() if distinct else None) 2744 return instance
Set the OFFSET expression.
Example:
>>> Select().from_("tbl").select("x").distinct().sql() 'SELECT DISTINCT x FROM tbl'
Arguments:
- distinct (bool): whether the Select should be distinct
- copy (bool): if
False, modify this expression instance in-place.
Returns:
Select: the modified expression.
2746 def ctas(self, table, properties=None, dialect=None, copy=True, **opts) -> Create: 2747 """ 2748 Convert this expression to a CREATE TABLE AS statement. 2749 2750 Example: 2751 >>> Select().select("*").from_("tbl").ctas("x").sql() 2752 'CREATE TABLE x AS SELECT * FROM tbl' 2753 2754 Args: 2755 table (str | Expression): the SQL code string to parse as the table name. 2756 If another `Expression` instance is passed, it will be used as-is. 2757 properties (dict): an optional mapping of table properties 2758 dialect (str): the dialect used to parse the input table. 2759 copy (bool): if `False`, modify this expression instance in-place. 2760 opts (kwargs): other options to use to parse the input table. 2761 2762 Returns: 2763 Create: the CREATE TABLE AS expression 2764 """ 2765 instance = _maybe_copy(self, copy) 2766 table_expression = maybe_parse( 2767 table, 2768 into=Table, 2769 dialect=dialect, 2770 **opts, 2771 ) 2772 properties_expression = None 2773 if properties: 2774 properties_expression = Properties.from_dict(properties) 2775 2776 return Create( 2777 this=table_expression, 2778 kind="table", 2779 expression=instance, 2780 properties=properties_expression, 2781 )
Convert this expression to a CREATE TABLE AS statement.
Example:
>>> Select().select("*").from_("tbl").ctas("x").sql() 'CREATE TABLE x AS SELECT * FROM tbl'
Arguments:
- table (str | Expression): the SQL code string to parse as the table name.
If another
Expressioninstance is passed, it will be used as-is. - properties (dict): an optional mapping of table properties
- dialect (str): the dialect used to parse the input table.
- copy (bool): if
False, modify this expression instance in-place. - opts (kwargs): other options to use to parse the input table.
Returns:
Create: the CREATE TABLE AS expression
2783 def lock(self, update: bool = True, copy: bool = True) -> Select: 2784 """ 2785 Set the locking read mode for this expression. 2786 2787 Examples: 2788 >>> Select().select("x").from_("tbl").where("x = 'a'").lock().sql("mysql") 2789 "SELECT x FROM tbl WHERE x = 'a' FOR UPDATE" 2790 2791 >>> Select().select("x").from_("tbl").where("x = 'a'").lock(update=False).sql("mysql") 2792 "SELECT x FROM tbl WHERE x = 'a' FOR SHARE" 2793 2794 Args: 2795 update: if `True`, the locking type will be `FOR UPDATE`, else it will be `FOR SHARE`. 2796 copy: if `False`, modify this expression instance in-place. 2797 2798 Returns: 2799 The modified expression. 2800 """ 2801 2802 inst = _maybe_copy(self, copy) 2803 inst.set("lock", Lock(update=update)) 2804 2805 return inst
Set the locking read mode for this expression.
Examples:
>>> Select().select("x").from_("tbl").where("x = 'a'").lock().sql("mysql") "SELECT x FROM tbl WHERE x = 'a' FOR UPDATE">>> Select().select("x").from_("tbl").where("x = 'a'").lock(update=False).sql("mysql") "SELECT x FROM tbl WHERE x = 'a' FOR SHARE"
Arguments:
- update: if
True, the locking type will beFOR UPDATE, else it will beFOR SHARE. - copy: if
False, modify this expression instance in-place.
Returns:
The modified expression.
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
2820class Subquery(DerivedTable, Unionable): 2821 arg_types = { 2822 "this": True, 2823 "alias": False, 2824 "with": False, 2825 **QUERY_MODIFIERS, 2826 } 2827 2828 def unnest(self): 2829 """ 2830 Returns the first non subquery. 2831 """ 2832 expression = self 2833 while isinstance(expression, Subquery): 2834 expression = expression.this 2835 return expression 2836 2837 @property 2838 def is_star(self) -> bool: 2839 return self.this.is_star 2840 2841 @property 2842 def output_name(self): 2843 return self.alias
2828 def unnest(self): 2829 """ 2830 Returns the first non subquery. 2831 """ 2832 expression = self 2833 while isinstance(expression, Subquery): 2834 expression = expression.this 2835 return expression
Returns the first non subquery.
Name of the output column if this expression is a selection.
If the Expression has no output name, an empty string is returned.
Example:
>>> from sqlglot import parse_one >>> parse_one("SELECT a").expressions[0].output_name 'a' >>> parse_one("SELECT b AS c").expressions[0].output_name 'c' >>> parse_one("SELECT 1 + 2").expressions[0].output_name ''
Inherited Members
2846class TableSample(Expression): 2847 arg_types = { 2848 "this": False, 2849 "method": False, 2850 "bucket_numerator": False, 2851 "bucket_denominator": False, 2852 "bucket_field": False, 2853 "percent": False, 2854 "rows": False, 2855 "size": False, 2856 "seed": False, 2857 "kind": False, 2858 }
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
2861class Tag(Expression): 2862 """Tags are used for generating arbitrary sql like SELECT <span>x</span>.""" 2863 2864 arg_types = { 2865 "this": False, 2866 "prefix": False, 2867 "postfix": False, 2868 }
Tags are used for generating arbitrary sql like SELECT x.
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
2871class Pivot(Expression): 2872 arg_types = { 2873 "this": False, 2874 "alias": False, 2875 "expressions": True, 2876 "field": True, 2877 "unpivot": True, 2878 "columns": False, 2879 }
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
2882class Window(Expression): 2883 arg_types = { 2884 "this": True, 2885 "partition_by": False, 2886 "order": False, 2887 "spec": False, 2888 "alias": False, 2889 "over": False, 2890 "first": False, 2891 }
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
2894class WindowSpec(Expression): 2895 arg_types = { 2896 "kind": False, 2897 "start": False, 2898 "start_side": False, 2899 "end": False, 2900 "end_side": False, 2901 }
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
2908class Star(Expression): 2909 arg_types = {"except": False, "replace": False} 2910 2911 @property 2912 def name(self) -> str: 2913 return "*" 2914 2915 @property 2916 def output_name(self): 2917 return self.name
Name of the output column if this expression is a selection.
If the Expression has no output name, an empty string is returned.
Example:
>>> from sqlglot import parse_one >>> parse_one("SELECT a").expressions[0].output_name 'a' >>> parse_one("SELECT b AS c").expressions[0].output_name 'c' >>> parse_one("SELECT 1 + 2").expressions[0].output_name ''
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
2932class Null(Condition): 2933 arg_types: t.Dict[str, t.Any] = {} 2934 2935 @property 2936 def name(self) -> str: 2937 return "NULL"
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
2944class DataType(Expression): 2945 arg_types = { 2946 "this": True, 2947 "expressions": False, 2948 "nested": False, 2949 "values": False, 2950 "prefix": False, 2951 } 2952 2953 class Type(AutoName): 2954 CHAR = auto() 2955 NCHAR = auto() 2956 VARCHAR = auto() 2957 NVARCHAR = auto() 2958 TEXT = auto() 2959 MEDIUMTEXT = auto() 2960 LONGTEXT = auto() 2961 MEDIUMBLOB = auto() 2962 LONGBLOB = auto() 2963 BINARY = auto() 2964 VARBINARY = auto() 2965 INT = auto() 2966 UINT = auto() 2967 TINYINT = auto() 2968 UTINYINT = auto() 2969 SMALLINT = auto() 2970 USMALLINT = auto() 2971 BIGINT = auto() 2972 UBIGINT = auto() 2973 FLOAT = auto() 2974 DOUBLE = auto() 2975 DECIMAL = auto() 2976 BIGDECIMAL = auto() 2977 BIT = auto() 2978 BOOLEAN = auto() 2979 JSON = auto() 2980 JSONB = auto() 2981 INTERVAL = auto() 2982 TIME = auto() 2983 TIMESTAMP = auto() 2984 TIMESTAMPTZ = auto() 2985 TIMESTAMPLTZ = auto() 2986 DATE = auto() 2987 DATETIME = auto() 2988 ARRAY = auto() 2989 MAP = auto() 2990 UUID = auto() 2991 GEOGRAPHY = auto() 2992 GEOMETRY = auto() 2993 STRUCT = auto() 2994 NULLABLE = auto() 2995 HLLSKETCH = auto() 2996 HSTORE = auto() 2997 SUPER = auto() 2998 SERIAL = auto() 2999 SMALLSERIAL = auto() 3000 BIGSERIAL = auto() 3001 XML = auto() 3002 UNIQUEIDENTIFIER = auto() 3003 MONEY = auto() 3004 SMALLMONEY = auto() 3005 ROWVERSION = auto() 3006 IMAGE = auto() 3007 VARIANT = auto() 3008 OBJECT = auto() 3009 INET = auto() 3010 NULL = auto() 3011 UNKNOWN = auto() # Sentinel value, useful for type annotation 3012 3013 TEXT_TYPES = { 3014 Type.CHAR, 3015 Type.NCHAR, 3016 Type.VARCHAR, 3017 Type.NVARCHAR, 3018 Type.TEXT, 3019 } 3020 3021 INTEGER_TYPES = { 3022 Type.INT, 3023 Type.TINYINT, 3024 Type.SMALLINT, 3025 Type.BIGINT, 3026 } 3027 3028 FLOAT_TYPES = { 3029 Type.FLOAT, 3030 Type.DOUBLE, 3031 } 3032 3033 NUMERIC_TYPES = {*INTEGER_TYPES, *FLOAT_TYPES} 3034 3035 TEMPORAL_TYPES = { 3036 Type.TIMESTAMP, 3037 Type.TIMESTAMPTZ, 3038 Type.TIMESTAMPLTZ, 3039 Type.DATE, 3040 Type.DATETIME, 3041 } 3042 3043 @classmethod 3044 def build( 3045 cls, dtype: str | DataType | DataType.Type, dialect: DialectType = None, **kwargs 3046 ) -> DataType: 3047 from sqlglot import parse_one 3048 3049 if isinstance(dtype, str): 3050 if dtype.upper() in cls.Type.__members__: 3051 data_type_exp: t.Optional[Expression] = DataType(this=DataType.Type[dtype.upper()]) 3052 else: 3053 data_type_exp = parse_one(dtype, read=dialect, into=DataType) 3054 if data_type_exp is None: 3055 raise ValueError(f"Unparsable data type value: {dtype}") 3056 elif isinstance(dtype, DataType.Type): 3057 data_type_exp = DataType(this=dtype) 3058 elif isinstance(dtype, DataType): 3059 return dtype 3060 else: 3061 raise ValueError(f"Invalid data type: {type(dtype)}. Expected str or DataType.Type") 3062 return DataType(**{**data_type_exp.args, **kwargs}) 3063 3064 def is_type(self, dtype: DataType.Type) -> bool: 3065 return self.this == dtype
3043 @classmethod 3044 def build( 3045 cls, dtype: str | DataType | DataType.Type, dialect: DialectType = None, **kwargs 3046 ) -> DataType: 3047 from sqlglot import parse_one 3048 3049 if isinstance(dtype, str): 3050 if dtype.upper() in cls.Type.__members__: 3051 data_type_exp: t.Optional[Expression] = DataType(this=DataType.Type[dtype.upper()]) 3052 else: 3053 data_type_exp = parse_one(dtype, read=dialect, into=DataType) 3054 if data_type_exp is None: 3055 raise ValueError(f"Unparsable data type value: {dtype}") 3056 elif isinstance(dtype, DataType.Type): 3057 data_type_exp = DataType(this=dtype) 3058 elif isinstance(dtype, DataType): 3059 return dtype 3060 else: 3061 raise ValueError(f"Invalid data type: {type(dtype)}. Expected str or DataType.Type") 3062 return DataType(**{**data_type_exp.args, **kwargs})
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
2953 class Type(AutoName): 2954 CHAR = auto() 2955 NCHAR = auto() 2956 VARCHAR = auto() 2957 NVARCHAR = auto() 2958 TEXT = auto() 2959 MEDIUMTEXT = auto() 2960 LONGTEXT = auto() 2961 MEDIUMBLOB = auto() 2962 LONGBLOB = auto() 2963 BINARY = auto() 2964 VARBINARY = auto() 2965 INT = auto() 2966 UINT = auto() 2967 TINYINT = auto() 2968 UTINYINT = auto() 2969 SMALLINT = auto() 2970 USMALLINT = auto() 2971 BIGINT = auto() 2972 UBIGINT = auto() 2973 FLOAT = auto() 2974 DOUBLE = auto() 2975 DECIMAL = auto() 2976 BIGDECIMAL = auto() 2977 BIT = auto() 2978 BOOLEAN = auto() 2979 JSON = auto() 2980 JSONB = auto() 2981 INTERVAL = auto() 2982 TIME = auto() 2983 TIMESTAMP = auto() 2984 TIMESTAMPTZ = auto() 2985 TIMESTAMPLTZ = auto() 2986 DATE = auto() 2987 DATETIME = auto() 2988 ARRAY = auto() 2989 MAP = auto() 2990 UUID = auto() 2991 GEOGRAPHY = auto() 2992 GEOMETRY = auto() 2993 STRUCT = auto() 2994 NULLABLE = auto() 2995 HLLSKETCH = auto() 2996 HSTORE = auto() 2997 SUPER = auto() 2998 SERIAL = auto() 2999 SMALLSERIAL = auto() 3000 BIGSERIAL = auto() 3001 XML = auto() 3002 UNIQUEIDENTIFIER = auto() 3003 MONEY = auto() 3004 SMALLMONEY = auto() 3005 ROWVERSION = auto() 3006 IMAGE = auto() 3007 VARIANT = auto() 3008 OBJECT = auto() 3009 INET = auto() 3010 NULL = auto() 3011 UNKNOWN = auto() # Sentinel value, useful for type annotation
An enumeration.
Inherited Members
- enum.Enum
- name
- value
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
3116class AddConstraint(Expression): 3117 arg_types = {"this": False, "expression": False, "enforced": False}
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
3125class Binary(Condition): 3126 arg_types = {"this": True, "expression": True} 3127 3128 @property 3129 def left(self): 3130 return self.this 3131 3132 @property 3133 def right(self): 3134 return self.expression
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
3181class Dot(Binary): 3182 @property 3183 def name(self) -> str: 3184 return self.expression.name 3185 3186 @classmethod 3187 def build(self, expressions: t.Sequence[Expression]) -> Dot: 3188 """Build a Dot object with a sequence of expressions.""" 3189 if len(expressions) < 2: 3190 raise ValueError(f"Dot requires >= 2 expressions.") 3191 3192 a, b, *expressions = expressions 3193 dot = Dot(this=a, expression=b) 3194 3195 for expression in expressions: 3196 dot = Dot(this=dot, expression=expression) 3197 3198 return dot
3186 @classmethod 3187 def build(self, expressions: t.Sequence[Expression]) -> Dot: 3188 """Build a Dot object with a sequence of expressions.""" 3189 if len(expressions) < 2: 3190 raise ValueError(f"Dot requires >= 2 expressions.") 3191 3192 a, b, *expressions = expressions 3193 dot = Dot(this=a, expression=b) 3194 3195 for expression in expressions: 3196 dot = Dot(this=dot, expression=expression) 3197 3198 return dot
Build a Dot object with a sequence of expressions.
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Kwarg in special functions like func(kwarg => y).
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
3323class Alias(Expression): 3324 arg_types = {"this": True, "alias": False} 3325 3326 @property 3327 def output_name(self): 3328 return self.alias
Name of the output column if this expression is a selection.
If the Expression has no output name, an empty string is returned.
Example:
>>> from sqlglot import parse_one >>> parse_one("SELECT a").expressions[0].output_name 'a' >>> parse_one("SELECT b AS c").expressions[0].output_name 'c' >>> parse_one("SELECT 1 + 2").expressions[0].output_name ''
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
3331class Aliases(Expression): 3332 arg_types = {"this": True, "expressions": True} 3333 3334 @property 3335 def aliases(self): 3336 return self.expressions
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
3355class In(Predicate): 3356 arg_types = { 3357 "this": True, 3358 "expressions": False, 3359 "query": False, 3360 "unnest": False, 3361 "field": False, 3362 "is_global": False, 3363 }
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
3366class TimeUnit(Expression): 3367 """Automatically converts unit arg into a var.""" 3368 3369 arg_types = {"unit": False} 3370 3371 def __init__(self, **args): 3372 unit = args.get("unit") 3373 if isinstance(unit, (Column, Literal)): 3374 args["unit"] = Var(this=unit.name) 3375 elif isinstance(unit, Week): 3376 unit.set("this", Var(this=unit.this.name)) 3377 super().__init__(**args)
Automatically converts unit arg into a var.
Inherited Members
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
3393class Func(Condition): 3394 """ 3395 The base class for all function expressions. 3396 3397 Attributes: 3398 is_var_len_args (bool): if set to True the last argument defined in arg_types will be 3399 treated as a variable length argument and the argument's value will be stored as a list. 3400 _sql_names (list): determines the SQL name (1st item in the list) and aliases (subsequent items) 3401 for this function expression. These values are used to map this node to a name during parsing 3402 as well as to provide the function's name during SQL string generation. By default the SQL 3403 name is set to the expression's class name transformed to snake case. 3404 """ 3405 3406 is_var_len_args = False 3407 3408 @classmethod 3409 def from_arg_list(cls, args): 3410 if cls.is_var_len_args: 3411 all_arg_keys = list(cls.arg_types) 3412 # If this function supports variable length argument treat the last argument as such. 3413 non_var_len_arg_keys = all_arg_keys[:-1] if cls.is_var_len_args else all_arg_keys 3414 num_non_var = len(non_var_len_arg_keys) 3415 3416 args_dict = {arg_key: arg for arg, arg_key in zip(args, non_var_len_arg_keys)} 3417 args_dict[all_arg_keys[-1]] = args[num_non_var:] 3418 else: 3419 args_dict = {arg_key: arg for arg, arg_key in zip(args, cls.arg_types)} 3420 3421 return cls(**args_dict) 3422 3423 @classmethod 3424 def sql_names(cls): 3425 if cls is Func: 3426 raise NotImplementedError( 3427 "SQL name is only supported by concrete function implementations" 3428 ) 3429 if "_sql_names" not in cls.__dict__: 3430 cls._sql_names = [camel_to_snake_case(cls.__name__)] 3431 return cls._sql_names 3432 3433 @classmethod 3434 def sql_name(cls): 3435 return cls.sql_names()[0] 3436 3437 @classmethod 3438 def default_parser_mappings(cls): 3439 return {name: cls.from_arg_list for name in cls.sql_names()}
The base class for all function expressions.
Attributes:
- is_var_len_args (bool): if set to True the last argument defined in arg_types will be treated as a variable length argument and the argument's value will be stored as a list.
- _sql_names (list): determines the SQL name (1st item in the list) and aliases (subsequent items) for this function expression. These values are used to map this node to a name during parsing as well as to provide the function's name during SQL string generation. By default the SQL name is set to the expression's class name transformed to snake case.
3408 @classmethod 3409 def from_arg_list(cls, args): 3410 if cls.is_var_len_args: 3411 all_arg_keys = list(cls.arg_types) 3412 # If this function supports variable length argument treat the last argument as such. 3413 non_var_len_arg_keys = all_arg_keys[:-1] if cls.is_var_len_args else all_arg_keys 3414 num_non_var = len(non_var_len_arg_keys) 3415 3416 args_dict = {arg_key: arg for arg, arg_key in zip(args, non_var_len_arg_keys)} 3417 args_dict[all_arg_keys[-1]] = args[num_non_var:] 3418 else: 3419 args_dict = {arg_key: arg for arg, arg_key in zip(args, cls.arg_types)} 3420 3421 return cls(**args_dict)
3423 @classmethod 3424 def sql_names(cls): 3425 if cls is Func: 3426 raise NotImplementedError( 3427 "SQL name is only supported by concrete function implementations" 3428 ) 3429 if "_sql_names" not in cls.__dict__: 3430 cls._sql_names = [camel_to_snake_case(cls.__name__)] 3431 return cls._sql_names
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
3450class Anonymous(Func): 3451 arg_types = {"this": True, "expressions": False} 3452 is_var_len_args = True
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
3457class Hll(AggFunc): 3458 arg_types = {"this": True, "expressions": False} 3459 is_var_len_args = True
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
3492class ArrayConcat(Func): 3493 arg_types = {"this": True, "expressions": False} 3494 is_var_len_args = True
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
3505class ArrayFilter(Func): 3506 arg_types = {"this": True, "expression": True} 3507 _sql_names = ["FILTER", "ARRAY_FILTER"]
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
3538class Case(Func): 3539 arg_types = {"this": False, "ifs": True, "default": False} 3540 3541 def when(self, condition: ExpOrStr, then: ExpOrStr, copy: bool = True, **opts) -> Case: 3542 this = self.copy() if copy else self 3543 this.append("ifs", If(this=maybe_parse(condition, **opts), true=maybe_parse(then, **opts))) 3544 return this 3545 3546 def else_(self, condition: ExpOrStr, copy: bool = True, **opts) -> Case: 3547 this = self.copy() if copy else self 3548 this.set("default", maybe_parse(condition, **opts)) 3549 return this
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
3552class Cast(Func): 3553 arg_types = {"this": True, "to": True} 3554 3555 @property 3556 def name(self) -> str: 3557 return self.this.name 3558 3559 @property 3560 def to(self): 3561 return self.args["to"] 3562 3563 @property 3564 def output_name(self): 3565 return self.name 3566 3567 def is_type(self, dtype: DataType.Type) -> bool: 3568 return self.to.is_type(dtype)
Name of the output column if this expression is a selection.
If the Expression has no output name, an empty string is returned.
Example:
>>> from sqlglot import parse_one >>> parse_one("SELECT a").expressions[0].output_name 'a' >>> parse_one("SELECT b AS c").expressions[0].output_name 'c' >>> parse_one("SELECT 1 + 2").expressions[0].output_name ''
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
3579class Ceil(Func): 3580 arg_types = {"this": True, "decimals": False} 3581 _sql_names = ["CEIL", "CEILING"]
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
3584class Coalesce(Func): 3585 arg_types = {"this": True, "expressions": False} 3586 is_var_len_args = True
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
3626class DateAdd(Func, TimeUnit): 3627 arg_types = {"this": True, "expression": True, "unit": False}
Inherited Members
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
3630class DateSub(Func, TimeUnit): 3631 arg_types = {"this": True, "expression": True, "unit": False}
Inherited Members
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
3634class DateDiff(Func, TimeUnit): 3635 _sql_names = ["DATEDIFF", "DATE_DIFF"] 3636 arg_types = {"this": True, "expression": True, "unit": False}
Inherited Members
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
3643class DatetimeAdd(Func, TimeUnit): 3644 arg_types = {"this": True, "expression": True, "unit": False}
Inherited Members
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
3647class DatetimeSub(Func, TimeUnit): 3648 arg_types = {"this": True, "expression": True, "unit": False}
Inherited Members
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
3651class DatetimeDiff(Func, TimeUnit): 3652 arg_types = {"this": True, "expression": True, "unit": False}
Inherited Members
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
3655class DatetimeTrunc(Func, TimeUnit): 3656 arg_types = {"this": True, "unit": True, "zone": False}
Inherited Members
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
3683class TimestampAdd(Func, TimeUnit): 3684 arg_types = {"this": True, "expression": True, "unit": False}
Inherited Members
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
3687class TimestampSub(Func, TimeUnit): 3688 arg_types = {"this": True, "expression": True, "unit": False}
Inherited Members
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
3691class TimestampDiff(Func, TimeUnit): 3692 arg_types = {"this": True, "expression": True, "unit": False}
Inherited Members
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
3695class TimestampTrunc(Func, TimeUnit): 3696 arg_types = {"this": True, "unit": True, "zone": False}
Inherited Members
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
3699class TimeAdd(Func, TimeUnit): 3700 arg_types = {"this": True, "expression": True, "unit": False}
Inherited Members
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
3703class TimeSub(Func, TimeUnit): 3704 arg_types = {"this": True, "expression": True, "unit": False}
Inherited Members
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
3707class TimeDiff(Func, TimeUnit): 3708 arg_types = {"this": True, "expression": True, "unit": False}
Inherited Members
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
3715class DateFromParts(Func): 3716 _sql_names = ["DATEFROMPARTS"] 3717 arg_types = {"year": True, "month": True, "day": True}
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
3756class ExponentialTimeDecayedAvg(AggFunc): 3757 arg_types = {"this": True, "time": False, "decay": False}
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
3764class Greatest(Func): 3765 arg_types = {"this": True, "expressions": False} 3766 is_var_len_args = True
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
3789class IfNull(Func): 3790 arg_types = {"this": True, "expression": False} 3791 _sql_names = ["IFNULL", "NVL"]
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
3802class JSONObject(Func): 3803 arg_types = { 3804 "expressions": False, 3805 "null_handling": False, 3806 "unique_keys": False, 3807 "return_type": False, 3808 "format_json": False, 3809 "encoding": False, 3810 }
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
3833class JSONFormat(Func): 3834 arg_types = {"this": False, "options": False} 3835 _sql_names = ["JSON_FORMAT"]
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
3847class Levenshtein(Func): 3848 arg_types = { 3849 "this": True, 3850 "expression": False, 3851 "ins_cost": False, 3852 "del_cost": False, 3853 "sub_cost": False, 3854 }
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
3899class MatchAgainst(Func): 3900 arg_types = {"this": True, "expressions": True, "modifier": False}
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
3903class Max(AggFunc): 3904 arg_types = {"this": True, "expressions": False} 3905 is_var_len_args = True
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
3912class Min(AggFunc): 3913 arg_types = {"this": True, "expressions": False} 3914 is_var_len_args = True
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
3947class Quantiles(AggFunc): 3948 arg_types = {"parameters": True, "expressions": True} 3949 is_var_len_args = True
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
3956class ApproxQuantile(Quantile): 3957 arg_types = {"this": True, "quantile": True, "accuracy": False, "weight": False}
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
3964class ReadCSV(Func): 3965 _sql_names = ["READ_CSV"] 3966 is_var_len_args = True 3967 arg_types = {"this": True, "expressions": False}
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
3970class Reduce(Func): 3971 arg_types = {"this": True, "initial": True, "merge": True, "finish": False}
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
3974class RegexpExtract(Func): 3975 arg_types = { 3976 "this": True, 3977 "expression": True, 3978 "position": False, 3979 "occurrence": False, 3980 "group": False, 3981 }
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
4041class StrPosition(Func): 4042 arg_types = { 4043 "this": True, 4044 "substr": True, 4045 "position": False, 4046 "instance": False, 4047 }
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
4121class Trim(Func): 4122 arg_types = { 4123 "this": True, 4124 "expression": False, 4125 "position": False, 4126 "collation": False, 4127 }
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
4130class TsOrDsAdd(Func, TimeUnit): 4131 arg_types = {"this": True, "expression": True, "unit": False}
Inherited Members
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
4156class UnixToTime(Func): 4157 arg_types = {"this": True, "scale": False, "zone": False, "hours": False, "minutes": False} 4158 4159 SECONDS = Literal.string("seconds") 4160 MILLIS = Literal.string("millis") 4161 MICROS = Literal.string("micros")
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
4184class XMLTable(Func): 4185 arg_types = {"this": True, "passing": False, "columns": False, "by_ref": False}
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
4196class Merge(Expression): 4197 arg_types = {"this": True, "using": True, "on": True, "expressions": True}
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
4200class When(Func): 4201 arg_types = {"matched": True, "source": False, "condition": False, "then": True}
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
4244def maybe_parse( 4245 sql_or_expression: ExpOrStr, 4246 *, 4247 into: t.Optional[IntoType] = None, 4248 dialect: DialectType = None, 4249 prefix: t.Optional[str] = None, 4250 copy: bool = False, 4251 **opts, 4252) -> Expression: 4253 """Gracefully handle a possible string or expression. 4254 4255 Example: 4256 >>> maybe_parse("1") 4257 (LITERAL this: 1, is_string: False) 4258 >>> maybe_parse(to_identifier("x")) 4259 (IDENTIFIER this: x, quoted: False) 4260 4261 Args: 4262 sql_or_expression: the SQL code string or an expression 4263 into: the SQLGlot Expression to parse into 4264 dialect: the dialect used to parse the input expressions (in the case that an 4265 input expression is a SQL string). 4266 prefix: a string to prefix the sql with before it gets parsed 4267 (automatically includes a space) 4268 copy: whether or not to copy the expression. 4269 **opts: other options to use to parse the input expressions (again, in the case 4270 that an input expression is a SQL string). 4271 4272 Returns: 4273 Expression: the parsed or given expression. 4274 """ 4275 if isinstance(sql_or_expression, Expression): 4276 if copy: 4277 return sql_or_expression.copy() 4278 return sql_or_expression 4279 4280 import sqlglot 4281 4282 sql = str(sql_or_expression) 4283 if prefix: 4284 sql = f"{prefix} {sql}" 4285 return sqlglot.parse_one(sql, read=dialect, into=into, **opts)
Gracefully handle a possible string or expression.
Example:
>>> maybe_parse("1") (LITERAL this: 1, is_string: False) >>> maybe_parse(to_identifier("x")) (IDENTIFIER this: x, quoted: False)
Arguments:
- sql_or_expression: the SQL code string or an expression
- into: the SQLGlot Expression to parse into
- dialect: the dialect used to parse the input expressions (in the case that an input expression is a SQL string).
- prefix: a string to prefix the sql with before it gets parsed (automatically includes a space)
- copy: whether or not to copy the expression.
- **opts: other options to use to parse the input expressions (again, in the case that an input expression is a SQL string).
Returns:
Expression: the parsed or given expression.
4431def union(left, right, distinct=True, dialect=None, **opts): 4432 """ 4433 Initializes a syntax tree from one UNION expression. 4434 4435 Example: 4436 >>> union("SELECT * FROM foo", "SELECT * FROM bla").sql() 4437 'SELECT * FROM foo UNION SELECT * FROM bla' 4438 4439 Args: 4440 left (str | Expression): the SQL code string corresponding to the left-hand side. 4441 If an `Expression` instance is passed, it will be used as-is. 4442 right (str | Expression): the SQL code string corresponding to the right-hand side. 4443 If an `Expression` instance is passed, it will be used as-is. 4444 distinct (bool): set the DISTINCT flag if and only if this is true. 4445 dialect (str): the dialect used to parse the input expression. 4446 opts (kwargs): other options to use to parse the input expressions. 4447 Returns: 4448 Union: the syntax tree for the UNION expression. 4449 """ 4450 left = maybe_parse(sql_or_expression=left, dialect=dialect, **opts) 4451 right = maybe_parse(sql_or_expression=right, dialect=dialect, **opts) 4452 4453 return Union(this=left, expression=right, distinct=distinct)
Initializes a syntax tree from one UNION expression.
Example:
>>> union("SELECT * FROM foo", "SELECT * FROM bla").sql() 'SELECT * FROM foo UNION SELECT * FROM bla'
Arguments:
- left (str | Expression): the SQL code string corresponding to the left-hand side.
If an
Expressioninstance is passed, it will be used as-is. - right (str | Expression): the SQL code string corresponding to the right-hand side.
If an
Expressioninstance is passed, it will be used as-is. - distinct (bool): set the DISTINCT flag if and only if this is true.
- dialect (str): the dialect used to parse the input expression.
- opts (kwargs): other options to use to parse the input expressions.
Returns:
Union: the syntax tree for the UNION expression.
4456def intersect(left, right, distinct=True, dialect=None, **opts): 4457 """ 4458 Initializes a syntax tree from one INTERSECT expression. 4459 4460 Example: 4461 >>> intersect("SELECT * FROM foo", "SELECT * FROM bla").sql() 4462 'SELECT * FROM foo INTERSECT SELECT * FROM bla' 4463 4464 Args: 4465 left (str | Expression): the SQL code string corresponding to the left-hand side. 4466 If an `Expression` instance is passed, it will be used as-is. 4467 right (str | Expression): the SQL code string corresponding to the right-hand side. 4468 If an `Expression` instance is passed, it will be used as-is. 4469 distinct (bool): set the DISTINCT flag if and only if this is true. 4470 dialect (str): the dialect used to parse the input expression. 4471 opts (kwargs): other options to use to parse the input expressions. 4472 Returns: 4473 Intersect: the syntax tree for the INTERSECT expression. 4474 """ 4475 left = maybe_parse(sql_or_expression=left, dialect=dialect, **opts) 4476 right = maybe_parse(sql_or_expression=right, dialect=dialect, **opts) 4477 4478 return Intersect(this=left, expression=right, distinct=distinct)
Initializes a syntax tree from one INTERSECT expression.
Example:
>>> intersect("SELECT * FROM foo", "SELECT * FROM bla").sql() 'SELECT * FROM foo INTERSECT SELECT * FROM bla'
Arguments:
- left (str | Expression): the SQL code string corresponding to the left-hand side.
If an
Expressioninstance is passed, it will be used as-is. - right (str | Expression): the SQL code string corresponding to the right-hand side.
If an
Expressioninstance is passed, it will be used as-is. - distinct (bool): set the DISTINCT flag if and only if this is true.
- dialect (str): the dialect used to parse the input expression.
- opts (kwargs): other options to use to parse the input expressions.
Returns:
Intersect: the syntax tree for the INTERSECT expression.
4481def except_(left, right, distinct=True, dialect=None, **opts): 4482 """ 4483 Initializes a syntax tree from one EXCEPT expression. 4484 4485 Example: 4486 >>> except_("SELECT * FROM foo", "SELECT * FROM bla").sql() 4487 'SELECT * FROM foo EXCEPT SELECT * FROM bla' 4488 4489 Args: 4490 left (str | Expression): the SQL code string corresponding to the left-hand side. 4491 If an `Expression` instance is passed, it will be used as-is. 4492 right (str | Expression): the SQL code string corresponding to the right-hand side. 4493 If an `Expression` instance is passed, it will be used as-is. 4494 distinct (bool): set the DISTINCT flag if and only if this is true. 4495 dialect (str): the dialect used to parse the input expression. 4496 opts (kwargs): other options to use to parse the input expressions. 4497 Returns: 4498 Except: the syntax tree for the EXCEPT statement. 4499 """ 4500 left = maybe_parse(sql_or_expression=left, dialect=dialect, **opts) 4501 right = maybe_parse(sql_or_expression=right, dialect=dialect, **opts) 4502 4503 return Except(this=left, expression=right, distinct=distinct)
Initializes a syntax tree from one EXCEPT expression.
Example:
>>> except_("SELECT * FROM foo", "SELECT * FROM bla").sql() 'SELECT * FROM foo EXCEPT SELECT * FROM bla'
Arguments:
- left (str | Expression): the SQL code string corresponding to the left-hand side.
If an
Expressioninstance is passed, it will be used as-is. - right (str | Expression): the SQL code string corresponding to the right-hand side.
If an
Expressioninstance is passed, it will be used as-is. - distinct (bool): set the DISTINCT flag if and only if this is true.
- dialect (str): the dialect used to parse the input expression.
- opts (kwargs): other options to use to parse the input expressions.
Returns:
Except: the syntax tree for the EXCEPT statement.
4506def select(*expressions: ExpOrStr, dialect: DialectType = None, **opts) -> Select: 4507 """ 4508 Initializes a syntax tree from one or multiple SELECT expressions. 4509 4510 Example: 4511 >>> select("col1", "col2").from_("tbl").sql() 4512 'SELECT col1, col2 FROM tbl' 4513 4514 Args: 4515 *expressions: the SQL code string to parse as the expressions of a 4516 SELECT statement. If an Expression instance is passed, this is used as-is. 4517 dialect: the dialect used to parse the input expressions (in the case that an 4518 input expression is a SQL string). 4519 **opts: other options to use to parse the input expressions (again, in the case 4520 that an input expression is a SQL string). 4521 4522 Returns: 4523 Select: the syntax tree for the SELECT statement. 4524 """ 4525 return Select().select(*expressions, dialect=dialect, **opts)
Initializes a syntax tree from one or multiple SELECT expressions.
Example:
>>> select("col1", "col2").from_("tbl").sql() 'SELECT col1, col2 FROM tbl'
Arguments:
- *expressions: the SQL code string to parse as the expressions of a SELECT statement. If an Expression instance is passed, this is used as-is.
- dialect: the dialect used to parse the input expressions (in the case that an input expression is a SQL string).
- **opts: other options to use to parse the input expressions (again, in the case that an input expression is a SQL string).
Returns:
Select: the syntax tree for the SELECT statement.
4528def from_(*expressions, dialect=None, **opts) -> Select: 4529 """ 4530 Initializes a syntax tree from a FROM expression. 4531 4532 Example: 4533 >>> from_("tbl").select("col1", "col2").sql() 4534 'SELECT col1, col2 FROM tbl' 4535 4536 Args: 4537 *expressions (str | Expression): the SQL code string to parse as the FROM expressions of a 4538 SELECT statement. If an Expression instance is passed, this is used as-is. 4539 dialect (str): the dialect used to parse the input expression (in the case that the 4540 input expression is a SQL string). 4541 **opts: other options to use to parse the input expressions (again, in the case 4542 that the input expression is a SQL string). 4543 4544 Returns: 4545 Select: the syntax tree for the SELECT statement. 4546 """ 4547 return Select().from_(*expressions, dialect=dialect, **opts)
Initializes a syntax tree from a FROM expression.
Example:
>>> from_("tbl").select("col1", "col2").sql() 'SELECT col1, col2 FROM tbl'
Arguments:
- *expressions (str | Expression): the SQL code string to parse as the FROM expressions of a SELECT statement. If an Expression instance is passed, this is used as-is.
- dialect (str): the dialect used to parse the input expression (in the case that the input expression is a SQL string).
- **opts: other options to use to parse the input expressions (again, in the case that the input expression is a SQL string).
Returns:
Select: the syntax tree for the SELECT statement.
4550def update( 4551 table: str | Table, 4552 properties: dict, 4553 where: t.Optional[ExpOrStr] = None, 4554 from_: t.Optional[ExpOrStr] = None, 4555 dialect: DialectType = None, 4556 **opts, 4557) -> Update: 4558 """ 4559 Creates an update statement. 4560 4561 Example: 4562 >>> update("my_table", {"x": 1, "y": "2", "z": None}, from_="baz", where="id > 1").sql() 4563 "UPDATE my_table SET x = 1, y = '2', z = NULL FROM baz WHERE id > 1" 4564 4565 Args: 4566 *properties: dictionary of properties to set which are 4567 auto converted to sql objects eg None -> NULL 4568 where: sql conditional parsed into a WHERE statement 4569 from_: sql statement parsed into a FROM statement 4570 dialect: the dialect used to parse the input expressions. 4571 **opts: other options to use to parse the input expressions. 4572 4573 Returns: 4574 Update: the syntax tree for the UPDATE statement. 4575 """ 4576 update_expr = Update(this=maybe_parse(table, into=Table, dialect=dialect)) 4577 update_expr.set( 4578 "expressions", 4579 [ 4580 EQ(this=maybe_parse(k, dialect=dialect, **opts), expression=convert(v)) 4581 for k, v in properties.items() 4582 ], 4583 ) 4584 if from_: 4585 update_expr.set( 4586 "from", 4587 maybe_parse(from_, into=From, dialect=dialect, prefix="FROM", **opts), 4588 ) 4589 if isinstance(where, Condition): 4590 where = Where(this=where) 4591 if where: 4592 update_expr.set( 4593 "where", 4594 maybe_parse(where, into=Where, dialect=dialect, prefix="WHERE", **opts), 4595 ) 4596 return update_expr
Creates an update statement.
Example:
>>> update("my_table", {"x": 1, "y": "2", "z": None}, from_="baz", where="id > 1").sql() "UPDATE my_table SET x = 1, y = '2', z = NULL FROM baz WHERE id > 1"
Arguments:
- *properties: dictionary of properties to set which are auto converted to sql objects eg None -> NULL
- where: sql conditional parsed into a WHERE statement
- from_: sql statement parsed into a FROM statement
- dialect: the dialect used to parse the input expressions.
- **opts: other options to use to parse the input expressions.
Returns:
Update: the syntax tree for the UPDATE statement.
4599def delete( 4600 table: ExpOrStr, 4601 where: t.Optional[ExpOrStr] = None, 4602 returning: t.Optional[ExpOrStr] = None, 4603 dialect: DialectType = None, 4604 **opts, 4605) -> Delete: 4606 """ 4607 Builds a delete statement. 4608 4609 Example: 4610 >>> delete("my_table", where="id > 1").sql() 4611 'DELETE FROM my_table WHERE id > 1' 4612 4613 Args: 4614 where: sql conditional parsed into a WHERE statement 4615 returning: sql conditional parsed into a RETURNING statement 4616 dialect: the dialect used to parse the input expressions. 4617 **opts: other options to use to parse the input expressions. 4618 4619 Returns: 4620 Delete: the syntax tree for the DELETE statement. 4621 """ 4622 delete_expr = Delete().delete(table, dialect=dialect, copy=False, **opts) 4623 if where: 4624 delete_expr = delete_expr.where(where, dialect=dialect, copy=False, **opts) 4625 if returning: 4626 delete_expr = delete_expr.returning(returning, dialect=dialect, copy=False, **opts) 4627 return delete_expr
Builds a delete statement.
Example:
>>> delete("my_table", where="id > 1").sql() 'DELETE FROM my_table WHERE id > 1'
Arguments:
- where: sql conditional parsed into a WHERE statement
- returning: sql conditional parsed into a RETURNING statement
- dialect: the dialect used to parse the input expressions.
- **opts: other options to use to parse the input expressions.
Returns:
Delete: the syntax tree for the DELETE statement.
4630def condition(expression, dialect=None, **opts) -> Condition: 4631 """ 4632 Initialize a logical condition expression. 4633 4634 Example: 4635 >>> condition("x=1").sql() 4636 'x = 1' 4637 4638 This is helpful for composing larger logical syntax trees: 4639 >>> where = condition("x=1") 4640 >>> where = where.and_("y=1") 4641 >>> Select().from_("tbl").select("*").where(where).sql() 4642 'SELECT * FROM tbl WHERE x = 1 AND y = 1' 4643 4644 Args: 4645 *expression (str | Expression): the SQL code string to parse. 4646 If an Expression instance is passed, this is used as-is. 4647 dialect (str): the dialect used to parse the input expression (in the case that the 4648 input expression is a SQL string). 4649 **opts: other options to use to parse the input expressions (again, in the case 4650 that the input expression is a SQL string). 4651 4652 Returns: 4653 Condition: the expression 4654 """ 4655 return maybe_parse( # type: ignore 4656 expression, 4657 into=Condition, 4658 dialect=dialect, 4659 **opts, 4660 )
Initialize a logical condition expression.
Example:
>>> condition("x=1").sql() 'x = 1'This is helpful for composing larger logical syntax trees:
>>> where = condition("x=1") >>> where = where.and_("y=1") >>> Select().from_("tbl").select("*").where(where).sql() 'SELECT * FROM tbl WHERE x = 1 AND y = 1'
Arguments:
- *expression (str | Expression): the SQL code string to parse. If an Expression instance is passed, this is used as-is.
- dialect (str): the dialect used to parse the input expression (in the case that the input expression is a SQL string).
- **opts: other options to use to parse the input expressions (again, in the case that the input expression is a SQL string).
Returns:
Condition: the expression
4663def and_(*expressions, dialect=None, **opts) -> And: 4664 """ 4665 Combine multiple conditions with an AND logical operator. 4666 4667 Example: 4668 >>> and_("x=1", and_("y=1", "z=1")).sql() 4669 'x = 1 AND (y = 1 AND z = 1)' 4670 4671 Args: 4672 *expressions (str | Expression): the SQL code strings to parse. 4673 If an Expression instance is passed, this is used as-is. 4674 dialect (str): the dialect used to parse the input expression. 4675 **opts: other options to use to parse the input expressions. 4676 4677 Returns: 4678 And: the new condition 4679 """ 4680 return _combine(expressions, And, dialect, **opts)
Combine multiple conditions with an AND logical operator.
Example:
>>> and_("x=1", and_("y=1", "z=1")).sql() 'x = 1 AND (y = 1 AND z = 1)'
Arguments:
- *expressions (str | Expression): the SQL code strings to parse. If an Expression instance is passed, this is used as-is.
- dialect (str): the dialect used to parse the input expression.
- **opts: other options to use to parse the input expressions.
Returns:
And: the new condition
4683def or_(*expressions, dialect=None, **opts) -> Or: 4684 """ 4685 Combine multiple conditions with an OR logical operator. 4686 4687 Example: 4688 >>> or_("x=1", or_("y=1", "z=1")).sql() 4689 'x = 1 OR (y = 1 OR z = 1)' 4690 4691 Args: 4692 *expressions (str | Expression): the SQL code strings to parse. 4693 If an Expression instance is passed, this is used as-is. 4694 dialect (str): the dialect used to parse the input expression. 4695 **opts: other options to use to parse the input expressions. 4696 4697 Returns: 4698 Or: the new condition 4699 """ 4700 return _combine(expressions, Or, dialect, **opts)
Combine multiple conditions with an OR logical operator.
Example:
>>> or_("x=1", or_("y=1", "z=1")).sql() 'x = 1 OR (y = 1 OR z = 1)'
Arguments:
- *expressions (str | Expression): the SQL code strings to parse. If an Expression instance is passed, this is used as-is.
- dialect (str): the dialect used to parse the input expression.
- **opts: other options to use to parse the input expressions.
Returns:
Or: the new condition
4703def not_(expression, dialect=None, **opts) -> Not: 4704 """ 4705 Wrap a condition with a NOT operator. 4706 4707 Example: 4708 >>> not_("this_suit='black'").sql() 4709 "NOT this_suit = 'black'" 4710 4711 Args: 4712 expression (str | Expression): the SQL code strings to parse. 4713 If an Expression instance is passed, this is used as-is. 4714 dialect (str): the dialect used to parse the input expression. 4715 **opts: other options to use to parse the input expressions. 4716 4717 Returns: 4718 Not: the new condition 4719 """ 4720 this = condition( 4721 expression, 4722 dialect=dialect, 4723 **opts, 4724 ) 4725 return Not(this=_wrap(this, Connector))
Wrap a condition with a NOT operator.
Example:
>>> not_("this_suit='black'").sql() "NOT this_suit = 'black'"
Arguments:
- expression (str | Expression): the SQL code strings to parse. If an Expression instance is passed, this is used as-is.
- dialect (str): the dialect used to parse the input expression.
- **opts: other options to use to parse the input expressions.
Returns:
Not: the new condition
4745def to_identifier(name, quoted=None): 4746 """Builds an identifier. 4747 4748 Args: 4749 name: The name to turn into an identifier. 4750 quoted: Whether or not force quote the identifier. 4751 4752 Returns: 4753 The identifier ast node. 4754 """ 4755 4756 if name is None: 4757 return None 4758 4759 if isinstance(name, Identifier): 4760 identifier = name 4761 elif isinstance(name, str): 4762 identifier = Identifier( 4763 this=name, 4764 quoted=not SAFE_IDENTIFIER_RE.match(name) if quoted is None else quoted, 4765 ) 4766 else: 4767 raise ValueError(f"Name needs to be a string or an Identifier, got: {name.__class__}") 4768 return identifier
Builds an identifier.
Arguments:
- name: The name to turn into an identifier.
- quoted: Whether or not force quote the identifier.
Returns:
The identifier ast node.
4774def to_interval(interval: str | Literal) -> Interval: 4775 """Builds an interval expression from a string like '1 day' or '5 months'.""" 4776 if isinstance(interval, Literal): 4777 if not interval.is_string: 4778 raise ValueError("Invalid interval string.") 4779 4780 interval = interval.this 4781 4782 interval_parts = INTERVAL_STRING_RE.match(interval) # type: ignore 4783 4784 if not interval_parts: 4785 raise ValueError("Invalid interval string.") 4786 4787 return Interval( 4788 this=Literal.string(interval_parts.group(1)), 4789 unit=Var(this=interval_parts.group(2)), 4790 )
Builds an interval expression from a string like '1 day' or '5 months'.
4803def to_table(sql_path: t.Optional[str | Table], **kwargs) -> t.Optional[Table]: 4804 """ 4805 Create a table expression from a `[catalog].[schema].[table]` sql path. Catalog and schema are optional. 4806 If a table is passed in then that table is returned. 4807 4808 Args: 4809 sql_path: a `[catalog].[schema].[table]` string. 4810 4811 Returns: 4812 A table expression. 4813 """ 4814 if sql_path is None or isinstance(sql_path, Table): 4815 return sql_path 4816 if not isinstance(sql_path, str): 4817 raise ValueError(f"Invalid type provided for a table: {type(sql_path)}") 4818 4819 catalog, db, table_name = (to_identifier(x) for x in split_num_words(sql_path, ".", 3)) 4820 return Table(this=table_name, db=db, catalog=catalog, **kwargs)
Create a table expression from a [catalog].[schema].[table] sql path. Catalog and schema are optional.
If a table is passed in then that table is returned.
Arguments:
- sql_path: a
[catalog].[schema].[table]string.
Returns:
A table expression.
4823def to_column(sql_path: str | Column, **kwargs) -> Column: 4824 """ 4825 Create a column from a `[table].[column]` sql path. Schema is optional. 4826 4827 If a column is passed in then that column is returned. 4828 4829 Args: 4830 sql_path: `[table].[column]` string 4831 Returns: 4832 Table: A column expression 4833 """ 4834 if sql_path is None or isinstance(sql_path, Column): 4835 return sql_path 4836 if not isinstance(sql_path, str): 4837 raise ValueError(f"Invalid type provided for column: {type(sql_path)}") 4838 return column(*reversed(sql_path.split(".")), **kwargs) # type: ignore
Create a column from a [table].[column] sql path. Schema is optional.
If a column is passed in then that column is returned.
Arguments:
- sql_path:
[table].[column]string
Returns:
Table: A column expression
4841def alias_( 4842 expression: ExpOrStr, 4843 alias: str | Identifier, 4844 table: bool | t.Sequence[str | Identifier] = False, 4845 quoted: t.Optional[bool] = None, 4846 dialect: DialectType = None, 4847 **opts, 4848): 4849 """Create an Alias expression. 4850 4851 Example: 4852 >>> alias_('foo', 'bar').sql() 4853 'foo AS bar' 4854 4855 >>> alias_('(select 1, 2)', 'bar', table=['a', 'b']).sql() 4856 '(SELECT 1, 2) AS bar(a, b)' 4857 4858 Args: 4859 expression: the SQL code strings to parse. 4860 If an Expression instance is passed, this is used as-is. 4861 alias: the alias name to use. If the name has 4862 special characters it is quoted. 4863 table: Whether or not to create a table alias, can also be a list of columns. 4864 quoted: whether or not to quote the alias 4865 dialect: the dialect used to parse the input expression. 4866 **opts: other options to use to parse the input expressions. 4867 4868 Returns: 4869 Alias: the aliased expression 4870 """ 4871 exp = maybe_parse(expression, dialect=dialect, **opts) 4872 alias = to_identifier(alias, quoted=quoted) 4873 4874 if table: 4875 table_alias = TableAlias(this=alias) 4876 4877 exp = exp.copy() if isinstance(expression, Expression) else exp 4878 exp.set("alias", table_alias) 4879 4880 if not isinstance(table, bool): 4881 for column in table: 4882 table_alias.append("columns", to_identifier(column, quoted=quoted)) 4883 4884 return exp 4885 4886 # We don't set the "alias" arg for Window expressions, because that would add an IDENTIFIER node in 4887 # the AST, representing a "named_window" [1] construct (eg. bigquery). What we want is an ALIAS node 4888 # for the complete Window expression. 4889 # 4890 # [1]: https://cloud.google.com/bigquery/docs/reference/standard-sql/window-function-calls 4891 4892 if "alias" in exp.arg_types and not isinstance(exp, Window): 4893 exp = exp.copy() 4894 exp.set("alias", alias) 4895 return exp 4896 return Alias(this=exp, alias=alias)
Create an Alias expression.
Example:
>>> alias_('foo', 'bar').sql() 'foo AS bar'>>> alias_('(select 1, 2)', 'bar', table=['a', 'b']).sql() '(SELECT 1, 2) AS bar(a, b)'
Arguments:
- expression: the SQL code strings to parse. If an Expression instance is passed, this is used as-is.
- alias: the alias name to use. If the name has special characters it is quoted.
- table: Whether or not to create a table alias, can also be a list of columns.
- quoted: whether or not to quote the alias
- dialect: the dialect used to parse the input expression.
- **opts: other options to use to parse the input expressions.
Returns:
Alias: the aliased expression
4899def subquery(expression, alias=None, dialect=None, **opts): 4900 """ 4901 Build a subquery expression. 4902 4903 Example: 4904 >>> subquery('select x from tbl', 'bar').select('x').sql() 4905 'SELECT x FROM (SELECT x FROM tbl) AS bar' 4906 4907 Args: 4908 expression (str | Expression): the SQL code strings to parse. 4909 If an Expression instance is passed, this is used as-is. 4910 alias (str | Expression): the alias name to use. 4911 dialect (str): the dialect used to parse the input expression. 4912 **opts: other options to use to parse the input expressions. 4913 4914 Returns: 4915 Select: a new select with the subquery expression included 4916 """ 4917 4918 expression = maybe_parse(expression, dialect=dialect, **opts).subquery(alias) 4919 return Select().from_(expression, dialect=dialect, **opts)
Build a subquery expression.
Example:
>>> subquery('select x from tbl', 'bar').select('x').sql() 'SELECT x FROM (SELECT x FROM tbl) AS bar'
Arguments:
- expression (str | Expression): the SQL code strings to parse. If an Expression instance is passed, this is used as-is.
- alias (str | Expression): the alias name to use.
- dialect (str): the dialect used to parse the input expression.
- **opts: other options to use to parse the input expressions.
Returns:
Select: a new select with the subquery expression included
4922def column( 4923 col: str | Identifier, 4924 table: t.Optional[str | Identifier] = None, 4925 db: t.Optional[str | Identifier] = None, 4926 catalog: t.Optional[str | Identifier] = None, 4927 quoted: t.Optional[bool] = None, 4928) -> Column: 4929 """ 4930 Build a Column. 4931 4932 Args: 4933 col: column name 4934 table: table name 4935 db: db name 4936 catalog: catalog name 4937 quoted: whether or not to force quote each part 4938 Returns: 4939 Column: column instance 4940 """ 4941 return Column( 4942 this=to_identifier(col, quoted=quoted), 4943 table=to_identifier(table, quoted=quoted), 4944 db=to_identifier(db, quoted=quoted), 4945 catalog=to_identifier(catalog, quoted=quoted), 4946 )
Build a Column.
Arguments:
- col: column name
- table: table name
- db: db name
- catalog: catalog name
- quoted: whether or not to force quote each part
Returns:
Column: column instance
4949def cast(expression: ExpOrStr, to: str | DataType | DataType.Type, **opts) -> Cast: 4950 """Cast an expression to a data type. 4951 4952 Example: 4953 >>> cast('x + 1', 'int').sql() 4954 'CAST(x + 1 AS INT)' 4955 4956 Args: 4957 expression: The expression to cast. 4958 to: The datatype to cast to. 4959 4960 Returns: 4961 A cast node. 4962 """ 4963 expression = maybe_parse(expression, **opts) 4964 return Cast(this=expression, to=DataType.build(to, **opts))
Cast an expression to a data type.
Example:
>>> cast('x + 1', 'int').sql() 'CAST(x + 1 AS INT)'
Arguments:
- expression: The expression to cast.
- to: The datatype to cast to.
Returns:
A cast node.
4967def table_(table, db=None, catalog=None, quoted=None, alias=None) -> Table: 4968 """Build a Table. 4969 4970 Args: 4971 table (str | Expression): column name 4972 db (str | Expression): db name 4973 catalog (str | Expression): catalog name 4974 4975 Returns: 4976 Table: table instance 4977 """ 4978 return Table( 4979 this=to_identifier(table, quoted=quoted), 4980 db=to_identifier(db, quoted=quoted), 4981 catalog=to_identifier(catalog, quoted=quoted), 4982 alias=TableAlias(this=to_identifier(alias)) if alias else None, 4983 )
Build a Table.
Arguments:
- table (str | Expression): column name
- db (str | Expression): db name
- catalog (str | Expression): catalog name
Returns:
Table: table instance
4986def values( 4987 values: t.Iterable[t.Tuple[t.Any, ...]], 4988 alias: t.Optional[str] = None, 4989 columns: t.Optional[t.Iterable[str] | t.Dict[str, DataType]] = None, 4990) -> Values: 4991 """Build VALUES statement. 4992 4993 Example: 4994 >>> values([(1, '2')]).sql() 4995 "VALUES (1, '2')" 4996 4997 Args: 4998 values: values statements that will be converted to SQL 4999 alias: optional alias 5000 columns: Optional list of ordered column names or ordered dictionary of column names to types. 5001 If either are provided then an alias is also required. 5002 If a dictionary is provided then the first column of the values will be casted to the expected type 5003 in order to help with type inference. 5004 5005 Returns: 5006 Values: the Values expression object 5007 """ 5008 if columns and not alias: 5009 raise ValueError("Alias is required when providing columns") 5010 table_alias = ( 5011 TableAlias(this=to_identifier(alias), columns=[to_identifier(x) for x in columns]) 5012 if columns 5013 else TableAlias(this=to_identifier(alias) if alias else None) 5014 ) 5015 expressions = [convert(tup) for tup in values] 5016 if columns and isinstance(columns, dict): 5017 types = list(columns.values()) 5018 expressions[0].set( 5019 "expressions", 5020 [cast(x, types[i]) for i, x in enumerate(expressions[0].expressions)], 5021 ) 5022 return Values( 5023 expressions=expressions, 5024 alias=table_alias, 5025 )
Build VALUES statement.
Example:
>>> values([(1, '2')]).sql() "VALUES (1, '2')"
Arguments:
- values: values statements that will be converted to SQL
- alias: optional alias
- columns: Optional list of ordered column names or ordered dictionary of column names to types. If either are provided then an alias is also required. If a dictionary is provided then the first column of the values will be casted to the expected type in order to help with type inference.
Returns:
Values: the Values expression object
5028def var(name: t.Optional[ExpOrStr]) -> Var: 5029 """Build a SQL variable. 5030 5031 Example: 5032 >>> repr(var('x')) 5033 '(VAR this: x)' 5034 5035 >>> repr(var(column('x', table='y'))) 5036 '(VAR this: x)' 5037 5038 Args: 5039 name: The name of the var or an expression who's name will become the var. 5040 5041 Returns: 5042 The new variable node. 5043 """ 5044 if not name: 5045 raise ValueError("Cannot convert empty name into var.") 5046 5047 if isinstance(name, Expression): 5048 name = name.name 5049 return Var(this=name)
Build a SQL variable.
Example:
>>> repr(var('x')) '(VAR this: x)'>>> repr(var(column('x', table='y'))) '(VAR this: x)'
Arguments:
- name: The name of the var or an expression who's name will become the var.
Returns:
The new variable node.
5052def rename_table(old_name: str | Table, new_name: str | Table) -> AlterTable: 5053 """Build ALTER TABLE... RENAME... expression 5054 5055 Args: 5056 old_name: The old name of the table 5057 new_name: The new name of the table 5058 5059 Returns: 5060 Alter table expression 5061 """ 5062 old_table = to_table(old_name) 5063 new_table = to_table(new_name) 5064 return AlterTable( 5065 this=old_table, 5066 actions=[ 5067 RenameTable(this=new_table), 5068 ], 5069 )
Build ALTER TABLE... RENAME... expression
Arguments:
- old_name: The old name of the table
- new_name: The new name of the table
Returns:
Alter table expression
5072def convert(value) -> Expression: 5073 """Convert a python value into an expression object. 5074 5075 Raises an error if a conversion is not possible. 5076 5077 Args: 5078 value (Any): a python object 5079 5080 Returns: 5081 Expression: the equivalent expression object 5082 """ 5083 if isinstance(value, Expression): 5084 return value 5085 if isinstance(value, str): 5086 return Literal.string(value) 5087 if isinstance(value, bool): 5088 return Boolean(this=value) 5089 if value is None or (isinstance(value, float) and math.isnan(value)): 5090 return NULL 5091 if isinstance(value, numbers.Number): 5092 return Literal.number(value) 5093 if isinstance(value, datetime.datetime): 5094 datetime_literal = Literal.string( 5095 (value if value.tzinfo else value.replace(tzinfo=datetime.timezone.utc)).isoformat() 5096 ) 5097 return TimeStrToTime(this=datetime_literal) 5098 if isinstance(value, datetime.date): 5099 date_literal = Literal.string(value.strftime("%Y-%m-%d")) 5100 return DateStrToDate(this=date_literal) 5101 if isinstance(value, tuple): 5102 return Tuple(expressions=[convert(v) for v in value]) 5103 if isinstance(value, list): 5104 return Array(expressions=[convert(v) for v in value]) 5105 if isinstance(value, dict): 5106 return Map( 5107 keys=[convert(k) for k in value], 5108 values=[convert(v) for v in value.values()], 5109 ) 5110 raise ValueError(f"Cannot convert {value}")
Convert a python value into an expression object.
Raises an error if a conversion is not possible.
Arguments:
- value (Any): a python object
Returns:
Expression: the equivalent expression object
5113def replace_children(expression, fun, *args, **kwargs): 5114 """ 5115 Replace children of an expression with the result of a lambda fun(child) -> exp. 5116 """ 5117 for k, v in expression.args.items(): 5118 is_list_arg = type(v) is list 5119 5120 child_nodes = v if is_list_arg else [v] 5121 new_child_nodes = [] 5122 5123 for cn in child_nodes: 5124 if isinstance(cn, Expression): 5125 for child_node in ensure_collection(fun(cn, *args, **kwargs)): 5126 new_child_nodes.append(child_node) 5127 child_node.parent = expression 5128 child_node.arg_key = k 5129 else: 5130 new_child_nodes.append(cn) 5131 5132 expression.args[k] = new_child_nodes if is_list_arg else seq_get(new_child_nodes, 0)
Replace children of an expression with the result of a lambda fun(child) -> exp.
5135def column_table_names(expression): 5136 """ 5137 Return all table names referenced through columns in an expression. 5138 5139 Example: 5140 >>> import sqlglot 5141 >>> column_table_names(sqlglot.parse_one("a.b AND c.d AND c.e")) 5142 ['c', 'a'] 5143 5144 Args: 5145 expression (sqlglot.Expression): expression to find table names 5146 5147 Returns: 5148 list: A list of unique names 5149 """ 5150 return list(dict.fromkeys(column.table for column in expression.find_all(Column)))
Return all table names referenced through columns in an expression.
Example:
>>> import sqlglot >>> column_table_names(sqlglot.parse_one("a.b AND c.d AND c.e")) ['c', 'a']
Arguments:
- expression (sqlglot.Expression): expression to find table names
Returns:
list: A list of unique names
5153def table_name(table) -> str: 5154 """Get the full name of a table as a string. 5155 5156 Args: 5157 table (exp.Table | str): table expression node or string. 5158 5159 Examples: 5160 >>> from sqlglot import exp, parse_one 5161 >>> table_name(parse_one("select * from a.b.c").find(exp.Table)) 5162 'a.b.c' 5163 5164 Returns: 5165 The table name. 5166 """ 5167 5168 table = maybe_parse(table, into=Table) 5169 5170 if not table: 5171 raise ValueError(f"Cannot parse {table}") 5172 5173 return ".".join( 5174 part 5175 for part in ( 5176 table.text("catalog"), 5177 table.text("db"), 5178 table.name, 5179 ) 5180 if part 5181 )
Get the full name of a table as a string.
Arguments:
- table (exp.Table | str): table expression node or string.
Examples:
>>> from sqlglot import exp, parse_one >>> table_name(parse_one("select * from a.b.c").find(exp.Table)) 'a.b.c'
Returns:
The table name.
5184def replace_tables(expression, mapping): 5185 """Replace all tables in expression according to the mapping. 5186 5187 Args: 5188 expression (sqlglot.Expression): expression node to be transformed and replaced. 5189 mapping (Dict[str, str]): mapping of table names. 5190 5191 Examples: 5192 >>> from sqlglot import exp, parse_one 5193 >>> replace_tables(parse_one("select * from a.b"), {"a.b": "c"}).sql() 5194 'SELECT * FROM c' 5195 5196 Returns: 5197 The mapped expression. 5198 """ 5199 5200 def _replace_tables(node): 5201 if isinstance(node, Table): 5202 new_name = mapping.get(table_name(node)) 5203 if new_name: 5204 return to_table( 5205 new_name, 5206 **{k: v for k, v in node.args.items() if k not in ("this", "db", "catalog")}, 5207 ) 5208 return node 5209 5210 return expression.transform(_replace_tables)
Replace all tables in expression according to the mapping.
Arguments:
- expression (sqlglot.Expression): expression node to be transformed and replaced.
- mapping (Dict[str, str]): mapping of table names.
Examples:
>>> from sqlglot import exp, parse_one >>> replace_tables(parse_one("select * from a.b"), {"a.b": "c"}).sql() 'SELECT * FROM c'
Returns:
The mapped expression.
5213def replace_placeholders(expression, *args, **kwargs): 5214 """Replace placeholders in an expression. 5215 5216 Args: 5217 expression (sqlglot.Expression): expression node to be transformed and replaced. 5218 args: positional names that will substitute unnamed placeholders in the given order. 5219 kwargs: keyword arguments that will substitute named placeholders. 5220 5221 Examples: 5222 >>> from sqlglot import exp, parse_one 5223 >>> replace_placeholders( 5224 ... parse_one("select * from :tbl where ? = ?"), 5225 ... exp.to_identifier("str_col"), "b", tbl=exp.to_identifier("foo") 5226 ... ).sql() 5227 "SELECT * FROM foo WHERE str_col = 'b'" 5228 5229 Returns: 5230 The mapped expression. 5231 """ 5232 5233 def _replace_placeholders(node, args, **kwargs): 5234 if isinstance(node, Placeholder): 5235 if node.name: 5236 new_name = kwargs.get(node.name) 5237 if new_name: 5238 return convert(new_name) 5239 else: 5240 try: 5241 return convert(next(args)) 5242 except StopIteration: 5243 pass 5244 return node 5245 5246 return expression.transform(_replace_placeholders, iter(args), **kwargs)
Replace placeholders in an expression.
Arguments:
- expression (sqlglot.Expression): expression node to be transformed and replaced.
- args: positional names that will substitute unnamed placeholders in the given order.
- kwargs: keyword arguments that will substitute named placeholders.
Examples:
>>> from sqlglot import exp, parse_one >>> replace_placeholders( ... parse_one("select * from :tbl where ? = ?"), ... exp.to_identifier("str_col"), "b", tbl=exp.to_identifier("foo") ... ).sql() "SELECT * FROM foo WHERE str_col = 'b'"
Returns:
The mapped expression.
5249def expand( 5250 expression: Expression, sources: t.Dict[str, Subqueryable], copy: bool = True 5251) -> Expression: 5252 """Transforms an expression by expanding all referenced sources into subqueries. 5253 5254 Examples: 5255 >>> from sqlglot import parse_one 5256 >>> expand(parse_one("select * from x AS z"), {"x": parse_one("select * from y")}).sql() 5257 'SELECT * FROM (SELECT * FROM y) AS z /* source: x */' 5258 5259 >>> expand(parse_one("select * from x AS z"), {"x": parse_one("select * from y"), "y": parse_one("select * from z")}).sql() 5260 'SELECT * FROM (SELECT * FROM (SELECT * FROM z) AS y /* source: y */) AS z /* source: x */' 5261 5262 Args: 5263 expression: The expression to expand. 5264 sources: A dictionary of name to Subqueryables. 5265 copy: Whether or not to copy the expression during transformation. Defaults to True. 5266 5267 Returns: 5268 The transformed expression. 5269 """ 5270 5271 def _expand(node: Expression): 5272 if isinstance(node, Table): 5273 name = table_name(node) 5274 source = sources.get(name) 5275 if source: 5276 subquery = source.subquery(node.alias or name) 5277 subquery.comments = [f"source: {name}"] 5278 return subquery.transform(_expand, copy=False) 5279 return node 5280 5281 return expression.transform(_expand, copy=copy)
Transforms an expression by expanding all referenced sources into subqueries.
Examples:
>>> from sqlglot import parse_one >>> expand(parse_one("select * from x AS z"), {"x": parse_one("select * from y")}).sql() 'SELECT * FROM (SELECT * FROM y) AS z /* source: x */'>>> expand(parse_one("select * from x AS z"), {"x": parse_one("select * from y"), "y": parse_one("select * from z")}).sql() 'SELECT * FROM (SELECT * FROM (SELECT * FROM z) AS y /* source: y */) AS z /* source: x */'
Arguments:
- expression: The expression to expand.
- sources: A dictionary of name to Subqueryables.
- copy: Whether or not to copy the expression during transformation. Defaults to True.
Returns:
The transformed expression.
5284def func(name: str, *args, dialect: DialectType = None, **kwargs) -> Func: 5285 """ 5286 Returns a Func expression. 5287 5288 Examples: 5289 >>> func("abs", 5).sql() 5290 'ABS(5)' 5291 5292 >>> func("cast", this=5, to=DataType.build("DOUBLE")).sql() 5293 'CAST(5 AS DOUBLE)' 5294 5295 Args: 5296 name: the name of the function to build. 5297 args: the args used to instantiate the function of interest. 5298 dialect: the source dialect. 5299 kwargs: the kwargs used to instantiate the function of interest. 5300 5301 Note: 5302 The arguments `args` and `kwargs` are mutually exclusive. 5303 5304 Returns: 5305 An instance of the function of interest, or an anonymous function, if `name` doesn't 5306 correspond to an existing `sqlglot.expressions.Func` class. 5307 """ 5308 if args and kwargs: 5309 raise ValueError("Can't use both args and kwargs to instantiate a function.") 5310 5311 from sqlglot.dialects.dialect import Dialect 5312 5313 converted: t.List[Expression] = [maybe_parse(arg, dialect=dialect) for arg in args] 5314 kwargs = {key: maybe_parse(value, dialect=dialect) for key, value in kwargs.items()} 5315 5316 parser = Dialect.get_or_raise(dialect)().parser() 5317 from_args_list = parser.FUNCTIONS.get(name.upper()) 5318 5319 if from_args_list: 5320 function = from_args_list(converted) if converted else from_args_list.__self__(**kwargs) # type: ignore 5321 else: 5322 kwargs = kwargs or {"expressions": converted} 5323 function = Anonymous(this=name, **kwargs) 5324 5325 for error_message in function.error_messages(converted): 5326 raise ValueError(error_message) 5327 5328 return function
Returns a Func expression.
Examples:
>>> func("abs", 5).sql() 'ABS(5)'>>> func("cast", this=5, to=DataType.build("DOUBLE")).sql() 'CAST(5 AS DOUBLE)'
Arguments:
- name: the name of the function to build.
- args: the args used to instantiate the function of interest.
- dialect: the source dialect.
- kwargs: the kwargs used to instantiate the function of interest.
Note:
The arguments
argsandkwargsare mutually exclusive.
Returns:
An instance of the function of interest, or an anonymous function, if
namedoesn't correspond to an existingsqlglot.expressions.Funcclass.
5331def true(): 5332 """ 5333 Returns a true Boolean expression. 5334 """ 5335 return Boolean(this=True)
Returns a true Boolean expression.
5338def false(): 5339 """ 5340 Returns a false Boolean expression. 5341 """ 5342 return Boolean(this=False)
Returns a false Boolean expression.
Returns a Null expression.